diff --git a/BUILD.gn b/BUILD.gn
index 47845cf3..cb6edd7 100644
--- a/BUILD.gn
+++ b/BUILD.gn
@@ -282,7 +282,7 @@
       "//content/shell/android:content_shell_apk",
       "//content/test:video_decode_accelerator_unittest",
       "//net/android:net_junit_tests",
-      "//testing/android/junit:junit_unittests",
+      "//testing/android/junit:junit_unit_tests",
       "//third_party/android_tools:uiautomator_java",
       "//third_party/errorprone:chromium_errorprone",
       "//third_party/smhasher:murmurhash3",
diff --git a/DEPS b/DEPS
index 0f8845b9..8e61ef12 100644
--- a/DEPS
+++ b/DEPS
@@ -39,7 +39,7 @@
   # Three lines of non-changing comments so that
   # the commit queue can handle CLs rolling Skia
   # and whatever else without interference from each other.
-  'skia_revision': '758586c7f11a6b3529bd4a1c9b4e982a0d0b0582',
+  'skia_revision': '044d3c185876f9960f07b88f068cf08d78311e33',
   # Three lines of non-changing comments so that
   # the commit queue can handle CLs rolling V8
   # and whatever else without interference from each other.
@@ -100,7 +100,7 @@
   # Three lines of non-changing comments so that
   # the commit queue can handle CLs rolling catapult
   # and whatever else without interference from each other.
-  'catapult_revision': '1224db2960f728efd09e327b3351dd2a690aae41',
+  'catapult_revision': '6ddc7cae0322ac1896c3009510454c000d1089b9',
   # Three lines of non-changing comments so that
   # the commit queue can handle CLs rolling libFuzzer
   # and whatever else without interference from each other.
@@ -220,7 +220,7 @@
    Var('chromium_git') + '/native_client/src/third_party/scons-2.0.1.git' + '@' + '1c1550e17fc26355d08627fbdec13d8291227067',
 
   'src/third_party/webrtc':
-    Var('chromium_git') + '/external/webrtc/trunk/webrtc.git' + '@' + '01047c5200ab33bf79e953f5f1bb05772169837f', # commit position 12264
+    Var('chromium_git') + '/external/webrtc/trunk/webrtc.git' + '@' + 'b7119195a1115ece827e5940693154322bf9b79d', # commit position 12274
 
   'src/third_party/openmax_dl':
     Var('chromium_git') + '/external/webrtc/deps/third_party/openmax.git' + '@' +  Var('openmax_dl_revision'),
diff --git a/base/synchronization/condition_variable.h b/base/synchronization/condition_variable.h
index a41b2ba..7dda21f 100644
--- a/base/synchronization/condition_variable.h
+++ b/base/synchronization/condition_variable.h
@@ -75,9 +75,12 @@
 #include <pthread.h>
 #endif
 
+#if defined(OS_WIN)
+#include <windows.h>
+#endif
+
 namespace base {
 
-class ConditionVarImpl;
 class TimeDelta;
 
 class BASE_EXPORT ConditionVariable {
@@ -100,14 +103,15 @@
  private:
 
 #if defined(OS_WIN)
-  ConditionVarImpl* impl_;
+  CONDITION_VARIABLE cv_;
+  CRITICAL_SECTION* const crit_sec_;
 #elif defined(OS_POSIX)
   pthread_cond_t condition_;
   pthread_mutex_t* user_mutex_;
-#if DCHECK_IS_ON()
-  base::Lock* user_lock_;     // Needed to adjust shadow lock state on wait.
 #endif
 
+#if DCHECK_IS_ON() && (defined(OS_WIN) || defined(OS_POSIX))
+  base::Lock* const user_lock_;  // Needed to adjust shadow lock state on wait.
 #endif
 
   DISALLOW_COPY_AND_ASSIGN(ConditionVariable);
diff --git a/base/synchronization/condition_variable_win.cc b/base/synchronization/condition_variable_win.cc
index 6812eb9..d598e33 100644
--- a/base/synchronization/condition_variable_win.cc
+++ b/base/synchronization/condition_variable_win.cc
@@ -4,666 +4,51 @@
 
 #include "base/synchronization/condition_variable.h"
 
-#include <windows.h>
-#include <stack>
-
-#include "base/compiler_specific.h"
-#include "base/macros.h"
 #include "base/synchronization/lock.h"
 #include "base/threading/thread_restrictions.h"
 #include "base/time/time.h"
 
-namespace {
-// We can't use the linker supported delay-load for kernel32 so all this
-// cruft here is to manually late-bind the needed functions.
-typedef void (WINAPI *InitializeConditionVariableFn)(PCONDITION_VARIABLE);
-typedef BOOL (WINAPI *SleepConditionVariableCSFn)(PCONDITION_VARIABLE,
-                                                  PCRITICAL_SECTION, DWORD);
-typedef void (WINAPI *WakeConditionVariableFn)(PCONDITION_VARIABLE);
-typedef void (WINAPI *WakeAllConditionVariableFn)(PCONDITION_VARIABLE);
-
-InitializeConditionVariableFn initialize_condition_variable_fn;
-SleepConditionVariableCSFn sleep_condition_variable_fn;
-WakeConditionVariableFn wake_condition_variable_fn;
-WakeAllConditionVariableFn wake_all_condition_variable_fn;
-
-bool BindVistaCondVarFunctions() {
-  HMODULE kernel32 = GetModuleHandleA("kernel32.dll");
-  initialize_condition_variable_fn =
-      reinterpret_cast<InitializeConditionVariableFn>(
-          GetProcAddress(kernel32, "InitializeConditionVariable"));
-  if (!initialize_condition_variable_fn)
-    return false;
-  sleep_condition_variable_fn =
-      reinterpret_cast<SleepConditionVariableCSFn>(
-          GetProcAddress(kernel32, "SleepConditionVariableCS"));
-  if (!sleep_condition_variable_fn)
-    return false;
-  wake_condition_variable_fn =
-      reinterpret_cast<WakeConditionVariableFn>(
-          GetProcAddress(kernel32, "WakeConditionVariable"));
-  if (!wake_condition_variable_fn)
-    return false;
-  wake_all_condition_variable_fn =
-      reinterpret_cast<WakeAllConditionVariableFn>(
-          GetProcAddress(kernel32, "WakeAllConditionVariable"));
-  if (!wake_all_condition_variable_fn)
-    return false;
-  return true;
-}
-
-}  // namespace.
-
 namespace base {
-// Abstract base class of the pimpl idiom.
-class ConditionVarImpl {
- public:
-  virtual ~ConditionVarImpl() {};
-  virtual void Wait() = 0;
-  virtual void TimedWait(const TimeDelta& max_time) = 0;
-  virtual void Broadcast() = 0;
-  virtual void Signal() = 0;
-};
-
-///////////////////////////////////////////////////////////////////////////////
-// Windows Vista and Win7 implementation.
-///////////////////////////////////////////////////////////////////////////////
-
-class WinVistaCondVar: public ConditionVarImpl {
- public:
-  WinVistaCondVar(Lock* user_lock);
-  ~WinVistaCondVar() override {}
-  // Overridden from ConditionVarImpl.
-  void Wait() override;
-  void TimedWait(const TimeDelta& max_time) override;
-  void Broadcast() override;
-  void Signal() override;
-
- private:
-  base::Lock& user_lock_;
-  CONDITION_VARIABLE cv_;
-};
-
-WinVistaCondVar::WinVistaCondVar(Lock* user_lock)
-    : user_lock_(*user_lock) {
-  initialize_condition_variable_fn(&cv_);
-  DCHECK(user_lock);
-}
-
-void WinVistaCondVar::Wait() {
-  TimedWait(TimeDelta::FromMilliseconds(INFINITE));
-}
-
-void WinVistaCondVar::TimedWait(const TimeDelta& max_time) {
-  base::ThreadRestrictions::AssertWaitAllowed();
-  DWORD timeout = static_cast<DWORD>(max_time.InMilliseconds());
-  CRITICAL_SECTION* cs = user_lock_.lock_.native_handle();
-
-#if DCHECK_IS_ON()
-  user_lock_.CheckHeldAndUnmark();
-#endif
-
-  if (FALSE == sleep_condition_variable_fn(&cv_, cs, timeout)) {
-    DCHECK(GetLastError() != WAIT_TIMEOUT);
-  }
-
-#if !defined(NDEBUG) || defined(DCHECK_ALWAYS_ON)
-  user_lock_.CheckUnheldAndMark();
-#endif
-}
-
-void WinVistaCondVar::Broadcast() {
-  wake_all_condition_variable_fn(&cv_);
-}
-
-void WinVistaCondVar::Signal() {
-  wake_condition_variable_fn(&cv_);
-}
-
-///////////////////////////////////////////////////////////////////////////////
-// Windows XP implementation.
-///////////////////////////////////////////////////////////////////////////////
-
-class WinXPCondVar : public ConditionVarImpl {
- public:
-  WinXPCondVar(Lock* user_lock);
-  ~WinXPCondVar() override;
-  // Overridden from ConditionVarImpl.
-  void Wait() override;
-  void TimedWait(const TimeDelta& max_time) override;
-  void Broadcast() override;
-  void Signal() override;
-
-  // Define Event class that is used to form circularly linked lists.
-  // The list container is an element with NULL as its handle_ value.
-  // The actual list elements have a non-zero handle_ value.
-  // All calls to methods MUST be done under protection of a lock so that links
-  // can be validated.  Without the lock, some links might asynchronously
-  // change, and the assertions would fail (as would list change operations).
-  class Event {
-   public:
-    // Default constructor with no arguments creates a list container.
-    Event();
-    ~Event();
-
-    // InitListElement transitions an instance from a container, to an element.
-    void InitListElement();
-
-    // Methods for use on lists.
-    bool IsEmpty() const;
-    void PushBack(Event* other);
-    Event* PopFront();
-    Event* PopBack();
-
-    // Methods for use on list elements.
-    // Accessor method.
-    HANDLE handle() const;
-    // Pull an element from a list (if it's in one).
-    Event* Extract();
-
-    // Method for use on a list element or on a list.
-    bool IsSingleton() const;
-
-   private:
-    // Provide pre/post conditions to validate correct manipulations.
-    bool ValidateAsDistinct(Event* other) const;
-    bool ValidateAsItem() const;
-    bool ValidateAsList() const;
-    bool ValidateLinks() const;
-
-    HANDLE handle_;
-    Event* next_;
-    Event* prev_;
-    DISALLOW_COPY_AND_ASSIGN(Event);
-  };
-
-  // Note that RUNNING is an unlikely number to have in RAM by accident.
-  // This helps with defensive destructor coding in the face of user error.
-  enum RunState { SHUTDOWN = 0, RUNNING = 64213 };
-
-  // Internal implementation methods supporting Wait().
-  Event* GetEventForWaiting();
-  void RecycleEvent(Event* used_event);
-
-  RunState run_state_;
-
-  // Private critical section for access to member data.
-  base::Lock internal_lock_;
-
-  // Lock that is acquired before calling Wait().
-  base::Lock& user_lock_;
-
-  // Events that threads are blocked on.
-  Event waiting_list_;
-
-  // Free list for old events.
-  Event recycling_list_;
-  int recycling_list_size_;
-
-  // The number of allocated, but not yet deleted events.
-  int allocation_counter_;
-};
-
-WinXPCondVar::WinXPCondVar(Lock* user_lock)
-    : run_state_(RUNNING),
-      user_lock_(*user_lock),
-      recycling_list_size_(0),
-      allocation_counter_(0) {
-  DCHECK(user_lock);
-}
-
-WinXPCondVar::~WinXPCondVar() {
-  AutoLock auto_lock(internal_lock_);
-  run_state_ = SHUTDOWN;  // Prevent any more waiting.
-
-  DCHECK_EQ(recycling_list_size_, allocation_counter_);
-  if (recycling_list_size_ != allocation_counter_) {  // Rare shutdown problem.
-    // There are threads of execution still in this->TimedWait() and yet the
-    // caller has instigated the destruction of this instance :-/.
-    // A common reason for such "overly hasty" destruction is that the caller
-    // was not willing to wait for all the threads to terminate.  Such hasty
-    // actions are a violation of our usage contract, but we'll give the
-    // waiting thread(s) one last chance to exit gracefully (prior to our
-    // destruction).
-    // Note: waiting_list_ *might* be empty, but recycling is still pending.
-    AutoUnlock auto_unlock(internal_lock_);
-    Broadcast();  // Make sure all waiting threads have been signaled.
-    Sleep(10);  // Give threads a chance to grab internal_lock_.
-    // All contained threads should be blocked on user_lock_ by now :-).
-  }  // Reacquire internal_lock_.
-
-  DCHECK_EQ(recycling_list_size_, allocation_counter_);
-}
-
-void WinXPCondVar::Wait() {
-  // Default to "wait forever" timing, which means have to get a Signal()
-  // or Broadcast() to come out of this wait state.
-  TimedWait(TimeDelta::FromMilliseconds(INFINITE));
-}
-
-void WinXPCondVar::TimedWait(const TimeDelta& max_time) {
-  base::ThreadRestrictions::AssertWaitAllowed();
-  Event* waiting_event;
-  HANDLE handle;
-  {
-    AutoLock auto_lock(internal_lock_);
-    if (RUNNING != run_state_) return;  // Destruction in progress.
-    waiting_event = GetEventForWaiting();
-    handle = waiting_event->handle();
-    DCHECK(handle);
-  }  // Release internal_lock.
-
-  {
-    AutoUnlock unlock(user_lock_);  // Release caller's lock
-    WaitForSingleObject(handle, static_cast<DWORD>(max_time.InMilliseconds()));
-    // Minimize spurious signal creation window by recycling asap.
-    AutoLock auto_lock(internal_lock_);
-    RecycleEvent(waiting_event);
-    // Release internal_lock_
-  }  // Reacquire callers lock to depth at entry.
-}
-
-// Broadcast() is guaranteed to signal all threads that were waiting (i.e., had
-// a cv_event internally allocated for them) before Broadcast() was called.
-void WinXPCondVar::Broadcast() {
-  std::stack<HANDLE> handles;  // See FAQ-question-10.
-  {
-    AutoLock auto_lock(internal_lock_);
-    if (waiting_list_.IsEmpty())
-      return;
-    while (!waiting_list_.IsEmpty())
-      // This is not a leak from waiting_list_.  See FAQ-question 12.
-      handles.push(waiting_list_.PopBack()->handle());
-  }  // Release internal_lock_.
-  while (!handles.empty()) {
-    SetEvent(handles.top());
-    handles.pop();
-  }
-}
-
-// Signal() will select one of the waiting threads, and signal it (signal its
-// cv_event).  For better performance we signal the thread that went to sleep
-// most recently (LIFO).  If we want fairness, then we wake the thread that has
-// been sleeping the longest (FIFO).
-void WinXPCondVar::Signal() {
-  HANDLE handle;
-  {
-    AutoLock auto_lock(internal_lock_);
-    if (waiting_list_.IsEmpty())
-      return;  // No one to signal.
-    // Only performance option should be used.
-    // This is not a leak from waiting_list.  See FAQ-question 12.
-     handle = waiting_list_.PopBack()->handle();  // LIFO.
-  }  // Release internal_lock_.
-  SetEvent(handle);
-}
-
-// GetEventForWaiting() provides a unique cv_event for any caller that needs to
-// wait.  This means that (worst case) we may over time create as many cv_event
-// objects as there are threads simultaneously using this instance's Wait()
-// functionality.
-WinXPCondVar::Event* WinXPCondVar::GetEventForWaiting() {
-  // We hold internal_lock, courtesy of Wait().
-  Event* cv_event;
-  if (0 == recycling_list_size_) {
-    DCHECK(recycling_list_.IsEmpty());
-    cv_event = new Event();
-    cv_event->InitListElement();
-    allocation_counter_++;
-    DCHECK(cv_event->handle());
-  } else {
-    cv_event = recycling_list_.PopFront();
-    recycling_list_size_--;
-  }
-  waiting_list_.PushBack(cv_event);
-  return cv_event;
-}
-
-// RecycleEvent() takes a cv_event that was previously used for Wait()ing, and
-// recycles it for use in future Wait() calls for this or other threads.
-// Note that there is a tiny chance that the cv_event is still signaled when we
-// obtain it, and that can cause spurious signals (if/when we re-use the
-// cv_event), but such is quite rare (see FAQ-question-5).
-void WinXPCondVar::RecycleEvent(Event* used_event) {
-  // We hold internal_lock, courtesy of Wait().
-  // If the cv_event timed out, then it is necessary to remove it from
-  // waiting_list_.  If it was selected by Broadcast() or Signal(), then it is
-  // already gone.
-  used_event->Extract();  // Possibly redundant
-  recycling_list_.PushBack(used_event);
-  recycling_list_size_++;
-}
-//------------------------------------------------------------------------------
-// The next section provides the implementation for the private Event class.
-//------------------------------------------------------------------------------
-
-// Event provides a doubly-linked-list of events for use exclusively by the
-// ConditionVariable class.
-
-// This custom container was crafted because no simple combination of STL
-// classes appeared to support the functionality required.  The specific
-// unusual requirement for a linked-list-class is support for the Extract()
-// method, which can remove an element from a list, potentially for insertion
-// into a second list.  Most critically, the Extract() method is idempotent,
-// turning the indicated element into an extracted singleton whether it was
-// contained in a list or not.  This functionality allows one (or more) of
-// threads to do the extraction.  The iterator that identifies this extractable
-// element (in this case, a pointer to the list element) can be used after
-// arbitrary manipulation of the (possibly) enclosing list container.  In
-// general, STL containers do not provide iterators that can be used across
-// modifications (insertions/extractions) of the enclosing containers, and
-// certainly don't provide iterators that can be used if the identified
-// element is *deleted* (removed) from the container.
-
-// It is possible to use multiple redundant containers, such as an STL list,
-// and an STL map, to achieve similar container semantics.  This container has
-// only O(1) methods, while the corresponding (multiple) STL container approach
-// would have more complex O(log(N)) methods (yeah... N isn't that large).
-// Multiple containers also makes correctness more difficult to assert, as
-// data is redundantly stored and maintained, which is generally evil.
-
-WinXPCondVar::Event::Event() : handle_(0) {
-  next_ = prev_ = this;  // Self referencing circular.
-}
-
-WinXPCondVar::Event::~Event() {
-  if (0 == handle_) {
-    // This is the list holder
-    while (!IsEmpty()) {
-      Event* cv_event = PopFront();
-      DCHECK(cv_event->ValidateAsItem());
-      delete cv_event;
-    }
-  }
-  DCHECK(IsSingleton());
-  if (0 != handle_) {
-    int ret_val = CloseHandle(handle_);
-    DCHECK(ret_val);
-  }
-}
-
-// Change a container instance permanently into an element of a list.
-void WinXPCondVar::Event::InitListElement() {
-  DCHECK(!handle_);
-  handle_ = CreateEvent(NULL, false, false, NULL);
-  DCHECK(handle_);
-}
-
-// Methods for use on lists.
-bool WinXPCondVar::Event::IsEmpty() const {
-  DCHECK(ValidateAsList());
-  return IsSingleton();
-}
-
-void WinXPCondVar::Event::PushBack(Event* other) {
-  DCHECK(ValidateAsList());
-  DCHECK(other->ValidateAsItem());
-  DCHECK(other->IsSingleton());
-  // Prepare other for insertion.
-  other->prev_ = prev_;
-  other->next_ = this;
-  // Cut into list.
-  prev_->next_ = other;
-  prev_ = other;
-  DCHECK(ValidateAsDistinct(other));
-}
-
-WinXPCondVar::Event* WinXPCondVar::Event::PopFront() {
-  DCHECK(ValidateAsList());
-  DCHECK(!IsSingleton());
-  return next_->Extract();
-}
-
-WinXPCondVar::Event* WinXPCondVar::Event::PopBack() {
-  DCHECK(ValidateAsList());
-  DCHECK(!IsSingleton());
-  return prev_->Extract();
-}
-
-// Methods for use on list elements.
-// Accessor method.
-HANDLE WinXPCondVar::Event::handle() const {
-  DCHECK(ValidateAsItem());
-  return handle_;
-}
-
-// Pull an element from a list (if it's in one).
-WinXPCondVar::Event* WinXPCondVar::Event::Extract() {
-  DCHECK(ValidateAsItem());
-  if (!IsSingleton()) {
-    // Stitch neighbors together.
-    next_->prev_ = prev_;
-    prev_->next_ = next_;
-    // Make extractee into a singleton.
-    prev_ = next_ = this;
-  }
-  DCHECK(IsSingleton());
-  return this;
-}
-
-// Method for use on a list element or on a list.
-bool WinXPCondVar::Event::IsSingleton() const {
-  DCHECK(ValidateLinks());
-  return next_ == this;
-}
-
-// Provide pre/post conditions to validate correct manipulations.
-bool WinXPCondVar::Event::ValidateAsDistinct(Event* other) const {
-  return ValidateLinks() && other->ValidateLinks() && (this != other);
-}
-
-bool WinXPCondVar::Event::ValidateAsItem() const {
-  return (0 != handle_) && ValidateLinks();
-}
-
-bool WinXPCondVar::Event::ValidateAsList() const {
-  return (0 == handle_) && ValidateLinks();
-}
-
-bool WinXPCondVar::Event::ValidateLinks() const {
-  // Make sure both of our neighbors have links that point back to us.
-  // We don't do the O(n) check and traverse the whole loop, and instead only
-  // do a local check to (and returning from) our immediate neighbors.
-  return (next_->prev_ == this) && (prev_->next_ == this);
-}
-
-
-/*
-FAQ On WinXPCondVar subtle implementation details:
-
-1) What makes this problem subtle?  Please take a look at "Strategies
-for Implementing POSIX Condition Variables on Win32" by Douglas
-C. Schmidt and Irfan Pyarali.
-http://www.cs.wustl.edu/~schmidt/win32-cv-1.html It includes
-discussions of numerous flawed strategies for implementing this
-functionality.  I'm not convinced that even the final proposed
-implementation has semantics that are as nice as this implementation
-(especially with regard to Broadcast() and the impact on threads that
-try to Wait() after a Broadcast() has been called, but before all the
-original waiting threads have been signaled).
-
-2) Why can't you use a single wait_event for all threads that call
-Wait()?  See FAQ-question-1, or consider the following: If a single
-event were used, then numerous threads calling Wait() could release
-their cs locks, and be preempted just before calling
-WaitForSingleObject().  If a call to Broadcast() was then presented on
-a second thread, it would be impossible to actually signal all
-waiting(?) threads.  Some number of SetEvent() calls *could* be made,
-but there could be no guarantee that those led to to more than one
-signaled thread (SetEvent()'s may be discarded after the first!), and
-there could be no guarantee that the SetEvent() calls didn't just
-awaken "other" threads that hadn't even started waiting yet (oops).
-Without any limit on the number of requisite SetEvent() calls, the
-system would be forced to do many such calls, allowing many new waits
-to receive spurious signals.
-
-3) How does this implementation cause spurious signal events?  The
-cause in this implementation involves a race between a signal via
-time-out and a signal via Signal() or Broadcast().  The series of
-actions leading to this are:
-
-a) Timer fires, and a waiting thread exits the line of code:
-
-    WaitForSingleObject(waiting_event, max_time.InMilliseconds());
-
-b) That thread (in (a)) is randomly pre-empted after the above line,
-leaving the waiting_event reset (unsignaled) and still in the
-waiting_list_.
-
-c) A call to Signal() (or Broadcast()) on a second thread proceeds, and
-selects the waiting cv_event (identified in step (b)) as the event to revive
-via a call to SetEvent().
-
-d) The Signal() method (step c) calls SetEvent() on waiting_event (step b).
-
-e) The waiting cv_event (step b) is now signaled, but no thread is
-waiting on it.
-
-f) When that waiting_event (step b) is reused, it will immediately
-be signaled (spuriously).
-
-
-4) Why do you recycle events, and cause spurious signals?  First off,
-the spurious events are very rare.  They can only (I think) appear
-when the race described in FAQ-question-3 takes place.  This should be
-very rare.  Most(?)  uses will involve only timer expiration, or only
-Signal/Broadcast() actions.  When both are used, it will be rare that
-the race will appear, and it would require MANY Wait() and signaling
-activities.  If this implementation did not recycle events, then it
-would have to create and destroy events for every call to Wait().
-That allocation/deallocation and associated construction/destruction
-would be costly (per wait), and would only be a rare benefit (when the
-race was "lost" and a spurious signal took place). That would be bad
-(IMO) optimization trade-off.  Finally, such spurious events are
-allowed by the specification of condition variables (such as
-implemented in Vista), and hence it is better if any user accommodates
-such spurious events (see usage note in condition_variable.h).
-
-5) Why don't you reset events when you are about to recycle them, or
-about to reuse them, so that the spurious signals don't take place?
-The thread described in FAQ-question-3 step c may be pre-empted for an
-arbitrary length of time before proceeding to step d.  As a result,
-the wait_event may actually be re-used *before* step (e) is reached.
-As a result, calling reset would not help significantly.
-
-6) How is it that the callers lock is released atomically with the
-entry into a wait state?  We commit to the wait activity when we
-allocate the wait_event for use in a given call to Wait().  This
-allocation takes place before the caller's lock is released (and
-actually before our internal_lock_ is released).  That allocation is
-the defining moment when "the wait state has been entered," as that
-thread *can* now be signaled by a call to Broadcast() or Signal().
-Hence we actually "commit to wait" before releasing the lock, making
-the pair effectively atomic.
-
-8) Why do you need to lock your data structures during waiting, as the
-caller is already in possession of a lock?  We need to Acquire() and
-Release() our internal lock during Signal() and Broadcast().  If we tried
-to use a callers lock for this purpose, we might conflict with their
-external use of the lock.  For example, the caller may use to consistently
-hold a lock on one thread while calling Signal() on another, and that would
-block Signal().
-
-9) Couldn't a more efficient implementation be provided if you
-preclude using more than one external lock in conjunction with a
-single ConditionVariable instance?  Yes, at least it could be viewed
-as a simpler API (since you don't have to reiterate the lock argument
-in each Wait() call).  One of the constructors now takes a specific
-lock as an argument, and a there are corresponding Wait() calls that
-don't specify a lock now.  It turns that the resulting implmentation
-can't be made more efficient, as the internal lock needs to be used by
-Signal() and Broadcast(), to access internal data structures.  As a
-result, I was not able to utilize the user supplied lock (which is
-being used by the user elsewhere presumably) to protect the private
-member access.
-
-9) Since you have a second lock, how can be be sure that there is no
-possible deadlock scenario?  Our internal_lock_ is always the last
-lock acquired, and the first one released, and hence a deadlock (due
-to critical section problems) is impossible as a consequence of our
-lock.
-
-10) When doing a Broadcast(), why did you copy all the events into
-an STL queue, rather than making a linked-loop, and iterating over it?
-The iterating during Broadcast() is done so outside the protection
-of the internal lock. As a result, other threads, such as the thread
-wherein a related event is waiting, could asynchronously manipulate
-the links around a cv_event.  As a result, the link structure cannot
-be used outside a lock.  Broadcast() could iterate over waiting
-events by cycling in-and-out of the protection of the internal_lock,
-but that appears more expensive than copying the list into an STL
-stack.
-
-11) Why did the lock.h file need to be modified so much for this
-change?  Central to a Condition Variable is the atomic release of a
-lock during a Wait().  This places Wait() functionality exactly
-mid-way between the two classes, Lock and Condition Variable.  Given
-that there can be nested Acquire()'s of locks, and Wait() had to
-Release() completely a held lock, it was necessary to augment the Lock
-class with a recursion counter. Even more subtle is the fact that the
-recursion counter (in a Lock) must be protected, as many threads can
-access it asynchronously.  As a positive fallout of this, there are
-now some DCHECKS to be sure no one Release()s a Lock more than they
-Acquire()ed it, and there is ifdef'ed functionality that can detect
-nested locks (legal under windows, but not under Posix).
-
-12) Why is it that the cv_events removed from list in Broadcast() and Signal()
-are not leaked?  How are they recovered??  The cv_events that appear to leak are
-taken from the waiting_list_.  For each element in that list, there is currently
-a thread in or around the WaitForSingleObject() call of Wait(), and those
-threads have references to these otherwise leaked events. They are passed as
-arguments to be recycled just aftre returning from WaitForSingleObject().
-
-13) Why did you use a custom container class (the linked list), when STL has
-perfectly good containers, such as an STL list?  The STL list, as with any
-container, does not guarantee the utility of an iterator across manipulation
-(such as insertions and deletions) of the underlying container.  The custom
-double-linked-list container provided that assurance.  I don't believe any
-combination of STL containers provided the services that were needed at the same
-O(1) efficiency as the custom linked list.  The unusual requirement
-for the container class is that a reference to an item within a container (an
-iterator) needed to be maintained across an arbitrary manipulation of the
-container.  This requirement exposes itself in the Wait() method, where a
-waiting_event must be selected prior to the WaitForSingleObject(), and then it
-must be used as part of recycling to remove the related instance from the
-waiting_list.  A hash table (STL map) could be used, but I was embarrased to
-use a complex and relatively low efficiency container when a doubly linked list
-provided O(1) performance in all required operations.  Since other operations
-to provide performance-and/or-fairness required queue (FIFO) and list (LIFO)
-containers, I would also have needed to use an STL list/queue as well as an STL
-map.  In the end I decided it would be "fun" to just do it right, and I
-put so many assertions (DCHECKs) into the container class that it is trivial to
-code review and validate its correctness.
-
-*/
 
 ConditionVariable::ConditionVariable(Lock* user_lock)
-    : impl_(NULL) {
-  static bool use_vista_native_cv = BindVistaCondVarFunctions();
-  if (use_vista_native_cv)
-    impl_= new WinVistaCondVar(user_lock);
-  else
-    impl_ = new WinXPCondVar(user_lock);
+    : crit_sec_(user_lock->lock_.native_handle())
+#if DCHECK_IS_ON()
+    , user_lock_(user_lock)
+#endif
+{
+  DCHECK(user_lock);
+  InitializeConditionVariable(&cv_);
 }
 
-ConditionVariable::~ConditionVariable() {
-  delete impl_;
-}
+ConditionVariable::~ConditionVariable() = default;
 
 void ConditionVariable::Wait() {
-  impl_->Wait();
+  TimedWait(TimeDelta::FromMilliseconds(INFINITE));
 }
 
 void ConditionVariable::TimedWait(const TimeDelta& max_time) {
-  impl_->TimedWait(max_time);
+  base::ThreadRestrictions::AssertWaitAllowed();
+  DWORD timeout = static_cast<DWORD>(max_time.InMilliseconds());
+
+#if DCHECK_IS_ON()
+  user_lock_->CheckHeldAndUnmark();
+#endif
+
+  if (FALSE == SleepConditionVariableCS(&cv_, crit_sec_, timeout)) {
+    DCHECK(GetLastError() != WAIT_TIMEOUT);
+  }
+
+#if DCHECK_IS_ON()
+  user_lock_->CheckUnheldAndMark();
+#endif
 }
 
 void ConditionVariable::Broadcast() {
-  impl_->Broadcast();
+  WakeAllConditionVariable(&cv_);
 }
 
 void ConditionVariable::Signal() {
-  impl_->Signal();
+  WakeConditionVariable(&cv_);
 }
 
 }  // namespace base
diff --git a/base/synchronization/lock.h b/base/synchronization/lock.h
index f7dd35d..39a26b77 100644
--- a/base/synchronization/lock.h
+++ b/base/synchronization/lock.h
@@ -61,15 +61,11 @@
   void AssertAcquired() const;
 #endif  // DCHECK_IS_ON()
 
-#if defined(OS_POSIX)
-  // The posix implementation of ConditionVariable needs to be able
-  // to see our lock and tweak our debugging counters, as it releases
-  // and acquires locks inside of pthread_cond_{timed,}wait.
+#if defined(OS_POSIX) || defined(OS_WIN)
+  // Both Windows and POSIX implementations of ConditionVariable need to be
+  // able to see our lock and tweak our debugging counters, as they release and
+  // acquire locks inside of their condition variable APIs.
   friend class ConditionVariable;
-#elif defined(OS_WIN)
-  // The Windows Vista implementation of ConditionVariable needs the
-  // native handle of the critical section.
-  friend class WinVistaCondVar;
 #endif
 
  private:
diff --git a/blimp/client/feature/compositor/blimp_gpu_memory_buffer_manager.cc b/blimp/client/feature/compositor/blimp_gpu_memory_buffer_manager.cc
index 8d1e624..4aae7d9 100644
--- a/blimp/client/feature/compositor/blimp_gpu_memory_buffer_manager.cc
+++ b/blimp/client/feature/compositor/blimp_gpu_memory_buffer_manager.cc
@@ -102,7 +102,9 @@
 std::unique_ptr<gfx::GpuMemoryBuffer>
 BlimpGpuMemoryBufferManager::AllocateGpuMemoryBuffer(const gfx::Size& size,
                                                      gfx::BufferFormat format,
-                                                     gfx::BufferUsage usage) {
+                                                     gfx::BufferUsage usage,
+                                                     int32_t surface_id) {
+  DCHECK_EQ(0, surface_id) << "Blimp should not be allocating scanout buffers";
   std::unique_ptr<base::SharedMemory> shared_memory(new base::SharedMemory);
   const size_t buffer_size = gfx::BufferSizeForBufferFormat(size, format);
   if (!shared_memory->CreateAnonymous(buffer_size))
diff --git a/blimp/client/feature/compositor/blimp_gpu_memory_buffer_manager.h b/blimp/client/feature/compositor/blimp_gpu_memory_buffer_manager.h
index 25afe20..cbd5552 100644
--- a/blimp/client/feature/compositor/blimp_gpu_memory_buffer_manager.h
+++ b/blimp/client/feature/compositor/blimp_gpu_memory_buffer_manager.h
@@ -20,7 +20,8 @@
   std::unique_ptr<gfx::GpuMemoryBuffer> AllocateGpuMemoryBuffer(
       const gfx::Size& size,
       gfx::BufferFormat format,
-      gfx::BufferUsage usage) override;
+      gfx::BufferUsage usage,
+      int32_t surface_id) override;
   std::unique_ptr<gfx::GpuMemoryBuffer> CreateGpuMemoryBufferFromHandle(
       const gfx::GpuMemoryBufferHandle& handle,
       const gfx::Size& size,
diff --git a/build/android/BUILD.gn b/build/android/BUILD.gn
index af819ed..9545243 100644
--- a/build/android/BUILD.gn
+++ b/build/android/BUILD.gn
@@ -44,7 +44,7 @@
 copy("cpplib_unstripped") {
   _soname = "libc++_shared.so"
   sources = [
-    "${android_libcpp_root}/libs/${android_app_abi}/${_soname}",
+    "${android_libcpp_lib_dir}/${_soname}",
   ]
   outputs = [
     "${root_out_dir}/lib.unstripped/${_soname}",
diff --git a/build/common.gypi b/build/common.gypi
index 0341654..0e88c8b 100644
--- a/build/common.gypi
+++ b/build/common.gypi
@@ -6149,6 +6149,11 @@
           ['_toolset=="target"', {
             'ldflags': [
               '-Wl,--plugin-opt,O1',
+              # Allows the linker to apply ICF to the LTO object file. Also, when
+              # targeting ARM, wWithout this flag, LTO produces a .text section
+              # that is larger than the maximum call displacement, preventing the
+              # linker from relocating calls (http://llvm.org/PR22999).
+              '-Wl,--plugin-opt,-function-sections',
             ],
           }],
           ['_toolset=="target" and _type!="static_library"', {
@@ -6168,20 +6173,6 @@
         },
       },
     }],
-    ['use_lto==1 and clang==1 and target_arch=="arm"', {
-      'target_defaults': {
-        'target_conditions': [
-          ['_toolset=="target"', {
-            # Without this flag, LTO produces a .text section that is larger
-            # than the maximum call displacement, preventing the linker from
-            # relocating calls (http://llvm.org/PR22999).
-            'ldflags': [
-              '-Wl,-plugin-opt,-function-sections',
-            ],
-          }],
-        ],
-      },
-    }],
     ['(use_lto==1 or use_lto_o2==1) and clang==0', {
       'target_defaults': {
         'target_conditions': [
@@ -6327,6 +6318,24 @@
         ],
       },
     }],
+    # TODO(pcc): Make these flags work correctly with CFI.
+    ['use_lto!=0 and cfi_vptr==0', {
+      'target_defaults': {
+        'target_conditions': [
+          ['_toolset=="target"', {
+            'cflags': [
+              '-fwhole-program-vtables',
+              # TODO(pcc): Remove this flag once the upstream interface change
+              # (http://reviews.llvm.org/D18635) lands.
+              '-fwhole-program-vtables-blacklist=<(cfi_blacklist)',
+            ],
+            'ldflags': [
+              '-fwhole-program-vtables',
+            ],
+          }],
+        ],
+      },
+    }],
   ],
   'xcode_settings': {
     # DON'T ADD ANYTHING NEW TO THIS BLOCK UNLESS YOU REALLY REALLY NEED IT!
diff --git a/build/config/android/BUILD.gn b/build/config/android/BUILD.gn
index 62c6d0c..0920ee8 100644
--- a/build/config/android/BUILD.gn
+++ b/build/config/android/BUILD.gn
@@ -143,7 +143,7 @@
 
   defines = [ "__GNU_SOURCE=1" ]  # Necessary for clone().
   ldflags = [ "-nostdlib" ]
-  lib_dirs = [ "$android_libcpp_root/libs/$android_app_abi" ]
+  lib_dirs = [ android_libcpp_lib_dir ]
 
   # The libc++ runtime library (must come first).
   # ASan needs to dynamically link to libc++ even in static builds so
diff --git a/build/config/android/config.gni b/build/config/android/config.gni
index 1009801c..16d5373 100644
--- a/build/config/android/config.gni
+++ b/build/config/android/config.gni
@@ -50,6 +50,9 @@
     android_sdk_version = default_android_sdk_version
     android_sdk_build_tools_version = default_android_sdk_build_tools_version
 
+    # Libc++ library directory. Override to use a custom libc++ binary.
+    android_libcpp_lib_dir = ""
+
     # Android versionCode for android_apk()s that don't expclitly set one.
     android_default_version_code = "1"
 
@@ -257,4 +260,8 @@
   } else {
     assert(false, "Unknown Android ABI: " + current_cpu)
   }
+
+  if (android_libcpp_lib_dir == "") {
+    android_libcpp_lib_dir = "${android_libcpp_root}/libs/${android_app_abi}"
+  }
 }
diff --git a/build/config/compiler/BUILD.gn b/build/config/compiler/BUILD.gn
index 0da129f..a59907b 100644
--- a/build/config/compiler/BUILD.gn
+++ b/build/config/compiler/BUILD.gn
@@ -7,6 +7,7 @@
 import("//build/config/compiler/compiler.gni")
 import("//build/config/nacl/config.gni")
 import("//build/toolchain/cc_wrapper.gni")
+import("//build/toolchain/toolchain.gni")
 
 if (current_cpu == "arm") {
   import("//build/config/arm.gni")
@@ -378,6 +379,52 @@
     }
   }
 
+  # Add flags for link-time optimization. These flags enable
+  # optimizations/transformations that require whole-program visibility at link
+  # time, so they need to be applied to all translation units, and we may end up
+  # with miscompiles if only part of the program is compiled with LTO flags. For
+  # that reason, we cannot allow targets to enable or disable these flags, for
+  # example by disabling the optimize configuration.
+  # TODO(pcc): Make this conditional on is_official_build rather than on gn
+  # flags for specific features.
+  if (!is_debug && (allow_posix_link_time_opt || is_cfi) && !is_nacl) {
+    cflags += [ "-flto" ]
+    ldflags += [ "-flto" ]
+
+    # Apply a lower LTO optimization level as the default is too slow.
+    if (is_linux) {
+      ldflags += [ "-Wl,-plugin-opt,O1" ]
+    } else if (is_mac) {
+      ldflags += [ "-Wl,-mllvm,-O1" ]
+    }
+
+    # Work-around for http://openradar.appspot.com/20356002
+    if (is_mac) {
+      ldflags += [ "-Wl,-all_load" ]
+    }
+
+    # Allows the linker to apply ICF to the LTO object file. Also, when
+    # targeting ARM, without this flag, LTO produces a .text section that is
+    # larger than the maximum call displacement, preventing the linker from
+    # relocating calls (http://llvm.org/PR22999).
+    if (is_linux) {
+      ldflags += [ "-Wl,-plugin-opt,-function-sections" ]
+    }
+
+    # TODO(pcc): Make these flags work correctly with CFI.
+    if (!is_cfi) {
+      cflags += [
+        "-fwhole-program-vtables",
+
+        # TODO(pcc): Remove this flag once the upstream interface change
+        # (http://reviews.llvm.org/D18635) lands.
+        "-fwhole-program-vtables-blacklist=" +
+            rebase_path("//tools/cfi/blacklist.txt", root_build_dir),
+      ]
+      ldflags += [ "-fwhole-program-vtables" ]
+    }
+  }
+
   # Pass the same C/C++ flags to the objective C/C++ compiler.
   cflags_objc += cflags_c
   cflags_objcc += cflags_cc
diff --git a/build/config/sanitizers/BUILD.gn b/build/config/sanitizers/BUILD.gn
index 3349723..29bb7f1c0 100644
--- a/build/config/sanitizers/BUILD.gn
+++ b/build/config/sanitizers/BUILD.gn
@@ -94,36 +94,13 @@
     if (is_ubsan_vptr) {
       ldflags += [ "-fsanitize=vptr" ]
     }
-    if (is_lto && !is_nacl) {
-      ldflags += [ "-flto" ]
 
-      # Apply a lower LTO optimization level as the default is too slow.
-      if (is_linux) {
-        ldflags += [ "-Wl,-plugin-opt,O1" ]
-      } else if (is_mac) {
-        ldflags += [ "-Wl,-mllvm,-O1" ]
-      }
-
-      # Work-around for http://openradar.appspot.com/20356002
-      if (is_mac) {
-        ldflags += [ "-Wl,-all_load" ]
-      }
-
-      # Without this flag, LTO produces a .text section that is larger
-      # than the maximum call displacement, preventing the linker from
-      # relocating calls (http://llvm.org/PR22999).
-      if (current_cpu == "arm") {
-        ldflags += [ "-Wl,-plugin-opt,-function-sections" ]
-      }
-
-      if (is_cfi) {
-        ldflags += [
-          "-fsanitize=cfi-vcall",
-          "-fsanitize=cfi-derived-cast",
-          "-fsanitize=cfi-unrelated-cast",
-        ]
-      }
-
+    if (is_cfi && !is_nacl) {
+      ldflags += [
+        "-fsanitize=cfi-vcall",
+        "-fsanitize=cfi-derived-cast",
+        "-fsanitize=cfi-unrelated-cast",
+      ]
       if (use_cfi_diag) {
         ldflags += [
           "-fno-sanitize-trap=cfi",
@@ -156,7 +133,7 @@
 
   # Common options for AddressSanitizer, LeakSanitizer, ThreadSanitizer,
   # MemorySanitizer and non-official CFI builds.
-  if (using_sanitizer || (is_lto && !is_official_build)) {
+  if (using_sanitizer || (is_cfi && !is_official_build)) {
     if (is_posix) {
       cflags += [ "-fno-omit-frame-pointer" ]
     } else {
@@ -282,19 +259,15 @@
       "-fsanitize-blacklist=$ubsan_blacklist_path",
     ]
   }
-  if (is_lto && !is_nacl) {
-    cflags += [ "-flto" ]
-
-    if (is_cfi) {
-      cfi_blacklist_path =
-          rebase_path("//tools/cfi/blacklist.txt", root_build_dir)
-      cflags += [
-        "-fsanitize=cfi-vcall",
-        "-fsanitize=cfi-derived-cast",
-        "-fsanitize=cfi-unrelated-cast",
-        "-fsanitize-blacklist=$cfi_blacklist_path",
-      ]
-    }
+  if (is_cfi && !is_nacl) {
+    cfi_blacklist_path =
+        rebase_path("//tools/cfi/blacklist.txt", root_build_dir)
+    cflags += [
+      "-fsanitize=cfi-vcall",
+      "-fsanitize=cfi-derived-cast",
+      "-fsanitize=cfi-unrelated-cast",
+      "-fsanitize-blacklist=$cfi_blacklist_path",
+    ]
 
     if (use_cfi_diag) {
       cflags += [
diff --git a/build/config/sanitizers/sanitizers.gni b/build/config/sanitizers/sanitizers.gni
index fd0989f..f407498 100644
--- a/build/config/sanitizers/sanitizers.gni
+++ b/build/config/sanitizers/sanitizers.gni
@@ -39,6 +39,8 @@
 
   # Compile with Control Flow Integrity to protect virtual calls and casts.
   # See http://clang.llvm.org/docs/ControlFlowIntegrity.html
+  #
+  # TODO(pcc): Remove this flag if/when CFI is enabled in official builds.
   is_cfi = false
 
   # By default, Control Flow Integrity will crash the program if it detects a
@@ -72,10 +74,6 @@
   use_custom_libcxx = (is_asan && is_linux) || is_tsan || is_msan || is_ubsan ||
                       is_ubsan_security || use_libfuzzer
 
-  # Enable Link Time Optimization (output programs runs faster,
-  # but linking is up to 5-20x slower.
-  is_lto = is_cfi
-
   use_sanitizer_coverage = use_libfuzzer
 }
 
diff --git a/build/toolchain/gcc_toolchain.gni b/build/toolchain/gcc_toolchain.gni
index 90f7779..e2b98e06 100644
--- a/build/toolchain/gcc_toolchain.gni
+++ b/build/toolchain/gcc_toolchain.gni
@@ -9,7 +9,7 @@
 import("//build/toolchain/toolchain.gni")
 
 # This value will be inherited in the toolchain below.
-if (is_lto) {
+if (allow_posix_link_time_opt || is_cfi) {
   concurrent_links =
       exec_script("get_concurrent_links.py", [ "--lto" ], "value")
 } else {
@@ -217,7 +217,8 @@
     tool("alink") {
       rspfile = "{{output}}.rsp"
       arflags = ""
-      if (is_lto && invoker.toolchain_os != "nacl") {
+      if ((allow_posix_link_time_opt || is_cfi) &&
+          invoker.toolchain_os != "nacl") {
         gold_plugin_path = rebase_path(
                 "//third_party/llvm-build/Release+Asserts/lib/LLVMgold.so",
                 root_build_dir)
diff --git a/build/toolchain/toolchain.gni b/build/toolchain/toolchain.gni
index e7f4379..41daacc 100644
--- a/build/toolchain/toolchain.gni
+++ b/build/toolchain/toolchain.gni
@@ -5,6 +5,14 @@
 # Toolchain-related configuration that may be needed outside the context of the
 # toolchain() rules themselves.
 
+declare_args() {
+  # Enable Link Time Optimization in optimized builds (output programs run
+  # faster, but linking is up to 5-20x slower).
+  #
+  # TODO(pcc): Remove this flag if/when LTO is enabled in official builds.
+  allow_posix_link_time_opt = false
+}
+
 # Subdirectory within root_out_dir for shared library files.
 # TODO(agrieve): GYP sets this to "lib" for Linux & Android, but this won't work
 #     in GN until support for loadable_module() is added.
diff --git a/build/toolchain/win/BUILD.gn b/build/toolchain/win/BUILD.gn
index c469c43..b0c5e279 100644
--- a/build/toolchain/win/BUILD.gn
+++ b/build/toolchain/win/BUILD.gn
@@ -25,12 +25,7 @@
 }
 
 # This value will be inherited in the toolchain below.
-if (is_lto) {
-  concurrent_links =
-      exec_script("../get_concurrent_links.py", [ "--lto" ], "value")
-} else {
-  concurrent_links = exec_script("../get_concurrent_links.py", [], "value")
-}
+concurrent_links = exec_script("../get_concurrent_links.py", [], "value")
 
 # Copy the VS runtime DLL for the default toolchain to the root build directory
 # so things will run.
diff --git a/cc/BUILD.gn b/cc/BUILD.gn
index ec16931..0f4ae41 100644
--- a/cc/BUILD.gn
+++ b/cc/BUILD.gn
@@ -829,6 +829,7 @@
     "layers/ui_resource_layer_unittest.cc",
     "layers/video_frame_provider_client_impl_unittest.cc",
     "layers/video_layer_impl_unittest.cc",
+    "layers/viewport_unittest.cc",
     "output/begin_frame_args_unittest.cc",
     "output/bsp_tree_unittest.cc",
     "output/delegating_renderer_unittest.cc",
diff --git a/cc/cc_tests.gyp b/cc/cc_tests.gyp
index 1d6ef72..785c560 100644
--- a/cc/cc_tests.gyp
+++ b/cc/cc_tests.gyp
@@ -68,6 +68,7 @@
       'layers/ui_resource_layer_unittest.cc',
       'layers/video_frame_provider_client_impl_unittest.cc',
       'layers/video_layer_impl_unittest.cc',
+      'layers/viewport_unittest.cc',
       'output/begin_frame_args_unittest.cc',
       'output/bsp_tree_unittest.cc',
       'output/delegating_renderer_unittest.cc',
diff --git a/cc/input/input_handler.h b/cc/input/input_handler.h
index 8aac2de..90870d9 100644
--- a/cc/input/input_handler.h
+++ b/cc/input/input_handler.h
@@ -99,6 +99,8 @@
     uint32_t main_thread_scrolling_reasons;
   };
 
+  // TODO(ymalik): Remove ANIMATED_WHEEL once it is no longer special cased.
+  // see crbug.com/575019.
   enum ScrollInputType {
     TOUCHSCREEN,
     WHEEL,
diff --git a/cc/layers/viewport.cc b/cc/layers/viewport.cc
index 1b3cfe57..b54c9cc 100644
--- a/cc/layers/viewport.cc
+++ b/cc/layers/viewport.cc
@@ -64,6 +64,62 @@
   return result;
 }
 
+bool Viewport::ShouldAnimateViewport(const gfx::Vector2dF& viewport_delta,
+                                     const gfx::Vector2dF& pending_delta) {
+  float max_dim_viewport_delta =
+      std::max(std::abs(viewport_delta.x()), std::abs(viewport_delta.y()));
+  float max_dim_pending_delta =
+      std::max(std::abs(pending_delta.x()), std::abs(pending_delta.y()));
+  return max_dim_viewport_delta > max_dim_pending_delta;
+}
+
+gfx::Vector2dF Viewport::ScrollAnimated(const gfx::Vector2dF& delta) {
+  ScrollTree& scroll_tree =
+      host_impl_->active_tree()->property_trees()->scroll_tree;
+
+  float scale_factor = host_impl_->active_tree()->current_page_scale_factor();
+  gfx::Vector2dF scaled_delta = delta;
+  scaled_delta.Scale(1.f / scale_factor);
+
+  ScrollNode* inner_node =
+      scroll_tree.Node(InnerScrollLayer()->scroll_tree_index());
+  gfx::Vector2dF inner_delta =
+      host_impl_->ComputeScrollDelta(inner_node, delta);
+
+  gfx::Vector2dF pending_delta = scaled_delta - inner_delta;
+  pending_delta.Scale(scale_factor);
+
+  ScrollNode* outer_node =
+      scroll_tree.Node(OuterScrollLayer()->scroll_tree_index());
+  gfx::Vector2dF outer_delta =
+      host_impl_->ComputeScrollDelta(outer_node, pending_delta);
+
+  if (inner_delta.IsZero() && outer_delta.IsZero())
+    return gfx::Vector2dF(0, 0);
+
+  // Animate the viewport to which the majority of scroll delta will be applied.
+  // The animation system only supports running one scroll offset animation.
+  // TODO(ymalik): Fix the visible jump seen by instant scrolling one of the
+  // viewports.
+  bool will_animate = false;
+  if (ShouldAnimateViewport(inner_delta, outer_delta)) {
+    scroll_tree.ScrollBy(outer_node, outer_delta, host_impl_->active_tree());
+    will_animate = host_impl_->ScrollAnimationCreate(inner_node, inner_delta);
+  } else {
+    scroll_tree.ScrollBy(inner_node, inner_delta, host_impl_->active_tree());
+    will_animate = host_impl_->ScrollAnimationCreate(outer_node, outer_delta);
+  }
+
+  if (will_animate) {
+    // Consume entire scroll delta as long as we are starting an animation.
+    return delta;
+  }
+
+  pending_delta = scaled_delta - inner_delta - outer_delta;
+  pending_delta.Scale(scale_factor);
+  return pending_delta;
+}
+
 void Viewport::SnapPinchAnchorIfWithinMargin(const gfx::Point& anchor) {
   gfx::SizeF viewport_size = gfx::SizeF(
       host_impl_->active_tree()->InnerViewportContainerLayer()->bounds());
diff --git a/cc/layers/viewport.h b/cc/layers/viewport.h
index 5052b5e..0c92881 100644
--- a/cc/layers/viewport.h
+++ b/cc/layers/viewport.h
@@ -5,6 +5,7 @@
 #ifndef CC_LAYERS_VIEWPORT_H_
 #define CC_LAYERS_VIEWPORT_H_
 
+#include "base/gtest_prod_util.h"
 #include "base/macros.h"
 #include "base/memory/scoped_ptr.h"
 #include "cc/layers/layer_impl.h"
@@ -46,12 +47,19 @@
                         bool is_wheel_scroll,
                         bool affect_top_controls);
 
+  // Scrolls the viewport, bubbling the delta between the inner and outer
+  // viewport. Only animates either of the two viewports.
+  gfx::Vector2dF ScrollAnimated(const gfx::Vector2dF& delta);
+
   void PinchUpdate(float magnify_delta, const gfx::Point& anchor);
   void PinchEnd();
 
  private:
   explicit Viewport(LayerTreeHostImpl* host_impl);
 
+  // Returns true if viewport_delta is stricly less than pending_delta.
+  static bool ShouldAnimateViewport(const gfx::Vector2dF& viewport_delta,
+                                    const gfx::Vector2dF& pending_delta);
   bool ShouldTopControlsConsumeScroll(const gfx::Vector2dF& scroll_delta) const;
   gfx::Vector2dF AdjustOverscroll(const gfx::Vector2dF& delta) const;
 
@@ -74,6 +82,8 @@
   // is used to "snap" a pinch-zoom to the edge of the screen.
   gfx::Vector2d pinch_anchor_adjustment_;
 
+  FRIEND_TEST_ALL_PREFIXES(ViewportTest, ShouldAnimateViewport);
+
   DISALLOW_COPY_AND_ASSIGN(Viewport);
 };
 
diff --git a/cc/layers/viewport_unittest.cc b/cc/layers/viewport_unittest.cc
new file mode 100644
index 0000000..d2646a2
--- /dev/null
+++ b/cc/layers/viewport_unittest.cc
@@ -0,0 +1,30 @@
+// Copyright 2016 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/viewport.h"
+
+#include <stddef.h>
+
+#include "cc/test/layer_test_common.h"
+#include "testing/gtest/include/gtest/gtest.h"
+
+namespace cc {
+
+TEST(ViewportTest, ShouldAnimateViewport) {
+  EXPECT_TRUE(Viewport::ShouldAnimateViewport(gfx::Vector2dF(10, 1),
+                                              gfx::Vector2dF(8, 5)));
+  EXPECT_TRUE(Viewport::ShouldAnimateViewport(gfx::Vector2dF(0, 10),
+                                              gfx::Vector2dF(4, 8)));
+  EXPECT_TRUE(Viewport::ShouldAnimateViewport(gfx::Vector2dF(10, 10),
+                                              gfx::Vector2dF(8, 9)));
+
+  EXPECT_FALSE(Viewport::ShouldAnimateViewport(gfx::Vector2dF(8, 10),
+                                               gfx::Vector2dF(8, 10)));
+  EXPECT_FALSE(Viewport::ShouldAnimateViewport(gfx::Vector2dF(8, 10),
+                                               gfx::Vector2dF(10, 0)));
+  EXPECT_FALSE(Viewport::ShouldAnimateViewport(gfx::Vector2dF(10, 10),
+                                               gfx::Vector2dF(10, 18)));
+}
+
+}  // namespace cc
diff --git a/cc/raster/one_copy_tile_task_worker_pool.cc b/cc/raster/one_copy_tile_task_worker_pool.cc
index 79429ad..8789119 100644
--- a/cc/raster/one_copy_tile_task_worker_pool.cc
+++ b/cc/raster/one_copy_tile_task_worker_pool.cc
@@ -344,7 +344,8 @@
                   staging_buffer->size, BufferFormat(resource->format()),
                   use_partial_raster_
                       ? gfx::BufferUsage::GPU_READ_CPU_READ_WRITE_PERSISTENT
-                      : gfx::BufferUsage::GPU_READ_CPU_READ_WRITE);
+                      : gfx::BufferUsage::GPU_READ_CPU_READ_WRITE,
+                  0 /* surface_id */);
     }
 
     gfx::Rect playback_rect = raster_full_rect;
diff --git a/cc/resources/resource_provider.cc b/cc/resources/resource_provider.cc
index b4e821d5..128ab28 100644
--- a/cc/resources/resource_provider.cc
+++ b/cc/resources/resource_provider.cc
@@ -1082,7 +1082,7 @@
     gpu_memory_buffer_ =
         resource_provider_->gpu_memory_buffer_manager_->AllocateGpuMemoryBuffer(
             resource_->size, BufferFormat(resource_->format),
-            gfx::BufferUsage::GPU_READ_CPU_READ_WRITE);
+            gfx::BufferUsage::GPU_READ_CPU_READ_WRITE, 0 /* surface_id */);
   }
   return gpu_memory_buffer_.get();
 }
@@ -1782,9 +1782,10 @@
   gl->BindTexture(resource->target, resource->gl_id);
   if (resource->type == RESOURCE_TYPE_GPU_MEMORY_BUFFER) {
     resource->gpu_memory_buffer =
-        gpu_memory_buffer_manager_->AllocateGpuMemoryBuffer(
-                                      size, BufferFormat(format),
-                                      gfx::BufferUsage::GPU_READ_CPU_READ_WRITE)
+        gpu_memory_buffer_manager_
+            ->AllocateGpuMemoryBuffer(size, BufferFormat(format),
+                                      gfx::BufferUsage::GPU_READ_CPU_READ_WRITE,
+                                      0 /* surface_id */)
             .release();
     LazyCreateImage(resource);
     resource->dirty_image = true;
diff --git a/cc/test/test_gpu_memory_buffer_manager.cc b/cc/test/test_gpu_memory_buffer_manager.cc
index a540e32..5cef8932 100644
--- a/cc/test/test_gpu_memory_buffer_manager.cc
+++ b/cc/test/test_gpu_memory_buffer_manager.cc
@@ -109,7 +109,8 @@
 scoped_ptr<gfx::GpuMemoryBuffer>
 TestGpuMemoryBufferManager::AllocateGpuMemoryBuffer(const gfx::Size& size,
                                                     gfx::BufferFormat format,
-                                                    gfx::BufferUsage usage) {
+                                                    gfx::BufferUsage usage,
+                                                    int32_t surface_id) {
   scoped_ptr<base::SharedMemory> shared_memory(new base::SharedMemory);
   const size_t buffer_size = gfx::BufferSizeForBufferFormat(size, format);
   if (!shared_memory->CreateAnonymous(buffer_size))
diff --git a/cc/test/test_gpu_memory_buffer_manager.h b/cc/test/test_gpu_memory_buffer_manager.h
index 5c693cb..7448fc3 100644
--- a/cc/test/test_gpu_memory_buffer_manager.h
+++ b/cc/test/test_gpu_memory_buffer_manager.h
@@ -23,7 +23,8 @@
   scoped_ptr<gfx::GpuMemoryBuffer> AllocateGpuMemoryBuffer(
       const gfx::Size& size,
       gfx::BufferFormat format,
-      gfx::BufferUsage usage) override;
+      gfx::BufferUsage usage,
+      int32_t surface_id) override;
   scoped_ptr<gfx::GpuMemoryBuffer> CreateGpuMemoryBufferFromHandle(
       const gfx::GpuMemoryBufferHandle& handle,
       const gfx::Size& size,
diff --git a/cc/trees/layer_tree_host_impl.cc b/cc/trees/layer_tree_host_impl.cc
index f0ce937..b013c8f4 100644
--- a/cc/trees/layer_tree_host_impl.cc
+++ b/cc/trees/layer_tree_host_impl.cc
@@ -2559,14 +2559,6 @@
   if (potentially_scrolling_layer_impl == OuterViewportScrollLayer())
     potentially_scrolling_layer_impl = InnerViewportScrollLayer();
 
-  // Animated wheel scrolls need to scroll the outer viewport layer, and do not
-  // go through Viewport::ScrollBy which would normally handle the distribution.
-  // NOTE: This will need refactoring if we want smooth scrolling on Android.
-  if (type == ANIMATED_WHEEL &&
-      potentially_scrolling_layer_impl == InnerViewportScrollLayer()) {
-    potentially_scrolling_layer_impl = OuterViewportScrollLayer();
-  }
-
   return potentially_scrolling_layer_impl;
 }
 
@@ -2722,6 +2714,54 @@
   return scroll_status;
 }
 
+gfx::Vector2dF LayerTreeHostImpl::ComputeScrollDelta(
+    ScrollNode* scroll_node,
+    const gfx::Vector2dF& delta) {
+  ScrollTree& scroll_tree = active_tree()->property_trees()->scroll_tree;
+  float scale_factor = active_tree()->current_page_scale_factor();
+
+  gfx::Vector2dF adjusted_scroll(delta);
+  adjusted_scroll.Scale(1.f / scale_factor);
+  if (!scroll_node->data.user_scrollable_horizontal)
+    adjusted_scroll.set_x(0);
+  if (!scroll_node->data.user_scrollable_vertical)
+    adjusted_scroll.set_y(0);
+
+  gfx::ScrollOffset old_offset =
+      scroll_tree.current_scroll_offset(scroll_node->owner_id);
+  gfx::ScrollOffset new_offset = scroll_tree.ClampScrollOffsetToLimits(
+      old_offset + gfx::ScrollOffset(adjusted_scroll), scroll_node);
+
+  gfx::ScrollOffset scrolled = new_offset - old_offset;
+  return gfx::Vector2dF(scrolled.x(), scrolled.y());
+}
+
+bool LayerTreeHostImpl::ScrollAnimationCreate(ScrollNode* scroll_node,
+                                              const gfx::Vector2dF& delta) {
+  ScrollTree& scroll_tree = active_tree_->property_trees()->scroll_tree;
+
+  const float kEpsilon = 0.1f;
+  bool scroll_animated =
+      (std::abs(delta.x()) > kEpsilon || std::abs(delta.y()) > kEpsilon);
+  if (!scroll_animated) {
+    scroll_tree.ScrollBy(scroll_node, delta, active_tree());
+    return false;
+  }
+
+  scroll_tree.set_currently_scrolling_node(scroll_node->id);
+
+  gfx::ScrollOffset current_offset =
+      scroll_tree.current_scroll_offset(scroll_node->owner_id);
+  gfx::ScrollOffset target_offset = scroll_tree.ClampScrollOffsetToLimits(
+      current_offset + gfx::ScrollOffset(delta), scroll_node);
+  animation_host_->ImplOnlyScrollAnimationCreate(scroll_node->owner_id,
+                                                 target_offset, current_offset);
+
+  SetNeedsOneBeginImplFrame();
+
+  return true;
+}
+
 InputHandler::ScrollStatus LayerTreeHostImpl::ScrollAnimated(
     const gfx::Point& viewport_point,
     const gfx::Vector2dF& scroll_delta) {
@@ -2764,42 +2804,26 @@
     if (scroll_node) {
       for (; scroll_tree.parent(scroll_node);
            scroll_node = scroll_tree.parent(scroll_node)) {
-        if (!scroll_node->data.scrollable)
+        if (!scroll_node->data.scrollable ||
+            scroll_node->data.is_outer_viewport_scroll_layer)
           continue;
 
-        gfx::ScrollOffset current_offset =
-            scroll_tree.current_scroll_offset(scroll_node->owner_id);
-        gfx::ScrollOffset target_offset =
-            ScrollOffsetWithDelta(current_offset, pending_delta);
-        target_offset.SetToMax(gfx::ScrollOffset());
-        target_offset.SetToMin(scroll_tree.MaxScrollOffset(scroll_node->id));
-        gfx::Vector2dF actual_delta = target_offset.DeltaFrom(current_offset);
-
-        if (!scroll_node->data.user_scrollable_horizontal) {
-          actual_delta.set_x(0);
-          target_offset.set_x(current_offset.x());
-        }
-        if (!scroll_node->data.user_scrollable_vertical) {
-          actual_delta.set_y(0);
-          target_offset.set_y(current_offset.y());
-        }
-
-        const float kEpsilon = 0.1f;
-        bool can_layer_scroll = (std::abs(actual_delta.x()) > kEpsilon ||
-                                 std::abs(actual_delta.y()) > kEpsilon);
-
-        if (!can_layer_scroll) {
-          scroll_tree.ScrollBy(scroll_node, actual_delta, active_tree());
-          pending_delta -= actual_delta;
+        if (scroll_node->data.is_inner_viewport_scroll_layer) {
+          gfx::Vector2dF scrolled = viewport()->ScrollAnimated(pending_delta);
+          // Viewport::ScrollAnimated returns pending_delta as long as it
+          // starts an animation.
+          if (scrolled == pending_delta)
+            return scroll_status;
+          pending_delta -= scrolled;
           continue;
         }
 
-        scroll_tree.set_currently_scrolling_node(scroll_node->id);
+        gfx::Vector2dF scroll_delta =
+            ComputeScrollDelta(scroll_node, pending_delta);
+        if (ScrollAnimationCreate(scroll_node, scroll_delta))
+          return scroll_status;
 
-        ScrollAnimationCreate(scroll_node, target_offset, current_offset);
-
-        SetNeedsOneBeginImplFrame();
-        return scroll_status;
+        pending_delta -= scroll_delta;
       }
     }
   }
@@ -3738,14 +3762,6 @@
   return animation_host_->ScrollAnimationAbort(false /* needs_completion */);
 }
 
-void LayerTreeHostImpl::ScrollAnimationCreate(
-    ScrollNode* scroll_node,
-    const gfx::ScrollOffset& target_offset,
-    const gfx::ScrollOffset& current_offset) {
-  return animation_host_->ImplOnlyScrollAnimationCreate(
-      scroll_node->owner_id, target_offset, current_offset);
-}
-
 bool LayerTreeHostImpl::ScrollAnimationUpdateTarget(
     ScrollNode* scroll_node,
     const gfx::Vector2dF& scroll_delta) {
diff --git a/cc/trees/layer_tree_host_impl.h b/cc/trees/layer_tree_host_impl.h
index a7d6b083..9366c22 100644
--- a/cc/trees/layer_tree_host_impl.h
+++ b/cc/trees/layer_tree_host_impl.h
@@ -536,6 +536,11 @@
     bool opaque;
   };
 
+  // Returns the amount of delta that can be applied to scroll_node, taking
+  // page scale into account.
+  gfx::Vector2dF ComputeScrollDelta(ScrollNode* scroll_node,
+                                    const gfx::Vector2dF& delta);
+
   void ScheduleMicroBenchmark(scoped_ptr<MicroBenchmarkImpl> benchmark);
 
   CompositorFrameMetadata MakeCompositorFrameMetadata() const;
@@ -616,6 +621,11 @@
                                        const ScrollTree& scroll_tree,
                                        ScrollNode* scroll_node) const;
 
+  // Returns true if a scroll offset animation is created and false if we scroll
+  // by the desired amount without an animation.
+  bool ScrollAnimationCreate(ScrollNode* scroll_node,
+                             const gfx::Vector2dF& scroll_amount);
+
  protected:
   LayerTreeHostImpl(
       const LayerTreeSettings& settings,
@@ -714,9 +724,6 @@
 
   void ScrollAnimationAbort(LayerImpl* layer_impl);
 
-  void ScrollAnimationCreate(ScrollNode* scroll_node,
-                             const gfx::ScrollOffset& target_offset,
-                             const gfx::ScrollOffset& current_offset);
   bool ScrollAnimationUpdateTarget(ScrollNode* scroll_node,
                                    const gfx::Vector2dF& scroll_delta);
 
diff --git a/cc/trees/layer_tree_host_impl_unittest.cc b/cc/trees/layer_tree_host_impl_unittest.cc
index f4284b64..31b8f56d 100644
--- a/cc/trees/layer_tree_host_impl_unittest.cc
+++ b/cc/trees/layer_tree_host_impl_unittest.cc
@@ -480,6 +480,15 @@
           layer_impl->id(), layer_impl->transform_tree_index());
   }
 
+  void BeginImplFrameAndAnimate(BeginFrameArgs begin_frame_args,
+                                base::TimeTicks frame_time) {
+    begin_frame_args.frame_time = frame_time;
+    host_impl_->WillBeginImplFrame(begin_frame_args);
+    host_impl_->Animate();
+    host_impl_->UpdateAnimationState(true);
+    host_impl_->DidFinishImplFrame();
+  }
+
   FakeImplTaskRunnerProvider task_runner_provider_;
   DebugScopedSetMainThreadBlocked always_main_thread_blocked_;
 
@@ -9518,11 +9527,9 @@
 }
 
 TEST_F(LayerTreeHostImplTest, ScrollAnimated) {
-  SetupScrollAndContentsLayers(gfx::Size(100, 200));
-
-  // Shrink the outer viewport clip layer so that the outer viewport can scroll.
-  host_impl_->OuterViewportScrollLayer()->parent()->SetBounds(
-      gfx::Size(50, 100));
+  const gfx::Size content_size(1000, 1000);
+  const gfx::Size viewport_size(50, 100);
+  CreateBasicVirtualViewportLayers(viewport_size, content_size);
 
   SetNeedsRebuildPropertyTrees();
   DrawFrame();
@@ -9779,6 +9786,153 @@
   host_impl_->DidFinishImplFrame();
 }
 
+// Test that the scroll delta for an animated scroll is distributed correctly
+// between the inner and outer viewport.
+TEST_F(LayerTreeHostImplTimelinesTest, ImplPinchZoomScrollAnimated) {
+  const gfx::Size content_size(200, 200);
+  const gfx::Size viewport_size(100, 100);
+  CreateBasicVirtualViewportLayers(viewport_size, content_size);
+
+  LayerImpl* outer_scroll_layer = host_impl_->OuterViewportScrollLayer();
+  LayerImpl* inner_scroll_layer = host_impl_->InnerViewportScrollLayer();
+
+  // Zoom into the page by a 2X factor
+  float min_page_scale = 1.f, max_page_scale = 4.f;
+  float page_scale_factor = 2.f;
+  RebuildPropertyTrees();
+  host_impl_->active_tree()->PushPageScaleFromMainThread(
+      page_scale_factor, min_page_scale, max_page_scale);
+  host_impl_->active_tree()->SetPageScaleOnActiveTree(page_scale_factor);
+
+  // Scroll by a small amount, there should be no bubbling to the outer
+  // viewport.
+  base::TimeTicks start_time =
+      base::TimeTicks() + base::TimeDelta::FromMilliseconds(250);
+  BeginFrameArgs begin_frame_args =
+      CreateBeginFrameArgsForTesting(BEGINFRAME_FROM_HERE);
+  EXPECT_EQ(InputHandler::SCROLL_ON_IMPL_THREAD,
+            host_impl_->ScrollAnimated(gfx::Point(), gfx::Vector2d(10.f, 20.f))
+                .thread);
+  host_impl_->Animate();
+  host_impl_->UpdateAnimationState(true);
+  EXPECT_EQ(inner_scroll_layer, host_impl_->CurrentlyScrollingLayer());
+
+  BeginImplFrameAndAnimate(begin_frame_args, start_time);
+  EXPECT_VECTOR_EQ(gfx::Vector2dF(5, 10),
+                   inner_scroll_layer->CurrentScrollOffset());
+  EXPECT_VECTOR_EQ(gfx::Vector2dF(0, 0),
+                   outer_scroll_layer->CurrentScrollOffset());
+  EXPECT_VECTOR_EQ(gfx::Vector2dF(), outer_scroll_layer->CurrentScrollOffset());
+
+  // Scroll by the inner viewport's max scroll extent, the remainder
+  // should bubble up to the outer viewport.
+  EXPECT_EQ(
+      InputHandler::SCROLL_ON_IMPL_THREAD,
+      host_impl_->ScrollAnimated(gfx::Point(), gfx::Vector2d(100.f, 100.f))
+          .thread);
+  host_impl_->Animate();
+  host_impl_->UpdateAnimationState(true);
+  EXPECT_EQ(inner_scroll_layer, host_impl_->CurrentlyScrollingLayer());
+
+  BeginImplFrameAndAnimate(begin_frame_args,
+                           start_time + base::TimeDelta::FromMilliseconds(350));
+  EXPECT_VECTOR_EQ(gfx::Vector2dF(50, 50),
+                   inner_scroll_layer->CurrentScrollOffset());
+  EXPECT_VECTOR_EQ(gfx::Vector2dF(5, 10),
+                   outer_scroll_layer->CurrentScrollOffset());
+
+  // Scroll by the outer viewport's max scroll extent, it should all go to the
+  // outer viewport.
+  EXPECT_EQ(
+      InputHandler::SCROLL_ON_IMPL_THREAD,
+      host_impl_->ScrollAnimated(gfx::Point(), gfx::Vector2d(190.f, 180.f))
+          .thread);
+  host_impl_->Animate();
+  host_impl_->UpdateAnimationState(true);
+  EXPECT_EQ(outer_scroll_layer, host_impl_->CurrentlyScrollingLayer());
+
+  BeginImplFrameAndAnimate(begin_frame_args,
+                           start_time + base::TimeDelta::FromMilliseconds(850));
+  EXPECT_VECTOR_EQ(gfx::Vector2dF(50, 50),
+                   inner_scroll_layer->CurrentScrollOffset());
+  EXPECT_VECTOR_EQ(gfx::Vector2dF(100, 100),
+                   outer_scroll_layer->CurrentScrollOffset());
+
+  // Scroll upwards by the max scroll extent. The inner viewport should animate
+  // and the remainder should bubble to the outer viewport.
+  EXPECT_EQ(
+      InputHandler::SCROLL_ON_IMPL_THREAD,
+      host_impl_->ScrollAnimated(gfx::Point(), gfx::Vector2d(-110.f, -120.f))
+          .thread);
+  host_impl_->Animate();
+  host_impl_->UpdateAnimationState(true);
+  EXPECT_EQ(inner_scroll_layer, host_impl_->CurrentlyScrollingLayer());
+
+  BeginImplFrameAndAnimate(
+      begin_frame_args, start_time + base::TimeDelta::FromMilliseconds(1200));
+  EXPECT_VECTOR_EQ(gfx::Vector2dF(0, 0),
+                   inner_scroll_layer->CurrentScrollOffset());
+  EXPECT_VECTOR_EQ(gfx::Vector2dF(95, 90),
+                   outer_scroll_layer->CurrentScrollOffset());
+}
+
+// Test that the correct viewport scroll layer is updated when the target offset
+// is updated.
+TEST_F(LayerTreeHostImplTimelinesTest, ImplPinchZoomScrollAnimatedUpdate) {
+  const gfx::Size content_size(200, 200);
+  const gfx::Size viewport_size(100, 100);
+  CreateBasicVirtualViewportLayers(viewport_size, content_size);
+
+  LayerImpl* outer_scroll_layer = host_impl_->OuterViewportScrollLayer();
+  LayerImpl* inner_scroll_layer = host_impl_->InnerViewportScrollLayer();
+
+  // Zoom into the page by a 2X factor
+  float min_page_scale = 1.f, max_page_scale = 4.f;
+  float page_scale_factor = 2.f;
+  RebuildPropertyTrees();
+  host_impl_->active_tree()->PushPageScaleFromMainThread(
+      page_scale_factor, min_page_scale, max_page_scale);
+  host_impl_->active_tree()->SetPageScaleOnActiveTree(page_scale_factor);
+
+  // Scroll the inner viewport.
+  base::TimeTicks start_time =
+      base::TimeTicks() + base::TimeDelta::FromMilliseconds(50);
+  BeginFrameArgs begin_frame_args =
+      CreateBeginFrameArgsForTesting(BEGINFRAME_FROM_HERE);
+  EXPECT_EQ(
+      InputHandler::SCROLL_ON_IMPL_THREAD,
+      host_impl_->ScrollAnimated(gfx::Point(), gfx::Vector2d(90, 90)).thread);
+  host_impl_->Animate();
+  host_impl_->UpdateAnimationState(true);
+  EXPECT_EQ(inner_scroll_layer, host_impl_->CurrentlyScrollingLayer());
+
+  BeginImplFrameAndAnimate(begin_frame_args, start_time);
+  float inner_x = inner_scroll_layer->CurrentScrollOffset().x();
+  float inner_y = inner_scroll_layer->CurrentScrollOffset().y();
+  EXPECT_TRUE(inner_x > 0 && inner_x < 45);
+  EXPECT_TRUE(inner_y > 0 && inner_y < 45);
+  EXPECT_VECTOR_EQ(gfx::Vector2dF(0, 0),
+                   outer_scroll_layer->CurrentScrollOffset());
+
+  // Update target.
+  EXPECT_EQ(
+      InputHandler::SCROLL_ON_IMPL_THREAD,
+      host_impl_->ScrollAnimated(gfx::Point(), gfx::Vector2d(50, 50)).thread);
+  host_impl_->Animate();
+  host_impl_->UpdateAnimationState(true);
+  EXPECT_EQ(inner_scroll_layer, host_impl_->CurrentlyScrollingLayer());
+
+  // Verify that all the delta is applied to the inner viewport and nothing is
+  // carried forward.
+  BeginImplFrameAndAnimate(begin_frame_args,
+                           start_time + base::TimeDelta::FromMilliseconds(350));
+  EXPECT_VECTOR_EQ(gfx::Vector2dF(50, 50),
+                   inner_scroll_layer->CurrentScrollOffset());
+  EXPECT_VECTOR_EQ(gfx::Vector2dF(0, 0),
+                   outer_scroll_layer->CurrentScrollOffset());
+  EXPECT_VECTOR_EQ(gfx::Vector2dF(), outer_scroll_layer->CurrentScrollOffset());
+}
+
 // Test that smooth scroll offset animation doesn't happen for non user
 // scrollable layers.
 TEST_F(LayerTreeHostImplTimelinesTest, ScrollAnimatedNotUserScrollable) {
diff --git a/cc/trees/property_tree.h b/cc/trees/property_tree.h
index e441ed8..b90010f 100644
--- a/cc/trees/property_tree.h
+++ b/cc/trees/property_tree.h
@@ -609,6 +609,8 @@
   gfx::Vector2dF ScrollBy(ScrollNode* scroll_node,
                           const gfx::Vector2dF& scroll,
                           LayerTreeImpl* layer_tree_impl);
+  gfx::ScrollOffset ClampScrollOffsetToLimits(gfx::ScrollOffset offset,
+                                              ScrollNode* scroll_node) const;
 
  private:
   int currently_scrolling_node_id_;
@@ -620,8 +622,6 @@
   void UpdateScrollOffsetMapEntry(int key,
                                   ScrollOffsetMap* new_scroll_offset_map,
                                   LayerTreeImpl* layer_tree_impl);
-  gfx::ScrollOffset ClampScrollOffsetToLimits(gfx::ScrollOffset offset,
-                                              ScrollNode* scroll_node) const;
 };
 
 class CC_EXPORT PropertyTrees final {
diff --git a/chrome/VERSION b/chrome/VERSION
index f027b10e..1247857 100644
--- a/chrome/VERSION
+++ b/chrome/VERSION
@@ -1,4 +1,4 @@
 MAJOR=51
 MINOR=0
-BUILD=2702
+BUILD=2703
 PATCH=0
diff --git a/chrome/android/BUILD.gn b/chrome/android/BUILD.gn
index 37b22b7..39b6c33 100644
--- a/chrome/android/BUILD.gn
+++ b/chrome/android/BUILD.gn
@@ -127,8 +127,11 @@
     "//media/base/android:media_java",
     "//media/capture/video/android:capture_java",
     "//media/midi:midi_java",
+    "//mojo/public/java:bindings",
+    "//mojo/public/java:system",
     "//net/android:net_java",
     "//printing:printing_java",
+    "//third_party/WebKit/public:android_mojo_bindings_java",
     "//third_party/WebKit/public:blink_headers_java",
     "//third_party/android_data_chart:android_data_chart_java",
     "//third_party/android_media:android_media_java",
diff --git a/chrome/android/java/res/layout/contextual_search_opt_out_promo.xml b/chrome/android/java/res/layout/contextual_search_promo_view.xml
similarity index 68%
rename from chrome/android/java/res/layout/contextual_search_opt_out_promo.xml
rename to chrome/android/java/res/layout/contextual_search_promo_view.xml
index 3d8c17d..e262beb6 100644
--- a/chrome/android/java/res/layout/contextual_search_opt_out_promo.xml
+++ b/chrome/android/java/res/layout/contextual_search_promo_view.xml
@@ -1,20 +1,23 @@
 <?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright 2015 The Chromium Authors. All rights reserved.
+<!-- Copyright 2016 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. -->
 
-<org.chromium.chrome.browser.compositor.bottombar.contextualsearch.ContextualSearchOptOutPromo
+<RelativeLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:chrome="http://schemas.android.com/apk/res-auto"
-    android:id="@+id/contextual_search_opt_out_promo"
+    android:id="@+id/contextual_search_promo"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:background="@drawable/contextual_search_promo_background"
-    android:orientation="vertical">
+    android:orientation="vertical"
+    android:visibility="invisible">
 
-    <!-- marginTop = 16dp - 9dp (margin above) -->
+    <!-- The top margin is supposed to be 16d, but the promo background already sets a
+         insetTop of 9dp (see contextual_search_promo_background.xml). For this reason,
+         we only should set the remaining margin top, which is 7dp -->
     <org.chromium.ui.widget.TextViewWithClickableSpans
-        android:id="@+id/contextual_search_opt_out_text"
+        android:id="@+id/contextual_search_promo_text"
         android:color="@color/contextual_search_promo_text_color"
         android:layout_alignParentTop="true"
         android:layout_alignParentStart="true"
@@ -28,8 +31,8 @@
         android:textSize="16sp" />
 
     <org.chromium.ui.widget.ButtonCompat
-        android:id="@+id/contextual_search_got_it_button"
-        android:layout_below="@id/contextual_search_opt_out_text"
+        android:id="@+id/contextual_search_allow_button"
+        android:layout_below="@id/contextual_search_promo_text"
         android:layout_alignParentEnd="true"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
@@ -39,16 +42,16 @@
         android:fontFamily="sans-serif-medium"
         android:paddingStart="8dp"
         android:paddingEnd="8dp"
-        android:text="@string/contextual_search_got_it_button"
+        android:text="@string/contextual_search_allow_button"
         android:textAllCaps="true"
         android:textColor="#FFF"
         android:textSize="14sp"
-        chrome:buttonColor="#4285F4" />
+        chrome:buttonColor="@color/light_active_color" />
 
     <Button
         android:id="@+id/contextual_search_no_thanks_button"
-        android:layout_below="@id/contextual_search_opt_out_text"
-        android:layout_toStartOf="@id/contextual_search_got_it_button"
+        android:layout_below="@id/contextual_search_promo_text"
+        android:layout_toStartOf="@id/contextual_search_allow_button"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_gravity="end"
@@ -64,10 +67,10 @@
         style="@style/ButtonCompatBorderless" />
 
     <View
-        android:layout_below="@id/contextual_search_got_it_button"
+        android:layout_below="@id/contextual_search_allow_button"
         android:layout_width="match_parent"
         android:layout_height="1px"
         android:layout_marginTop="16dp"
-        android:background="#c2c2c2" />
+        android:background="@color/contextual_search_promo_border_color" />
 
-</org.chromium.chrome.browser.compositor.bottombar.contextualsearch.ContextualSearchOptOutPromo>
+</RelativeLayout>
diff --git a/chrome/android/java/res/values/colors.xml b/chrome/android/java/res/values/colors.xml
index b2fb2b5b..68db0f4 100644
--- a/chrome/android/java/res/values/colors.xml
+++ b/chrome/android/java/res/values/colors.xml
@@ -108,6 +108,7 @@
     <!-- Contextual Search colors -->
     <color name="contextual_search_promo_text_color">#333333</color>
     <color name="contextual_search_promo_background_color">#EEEEEE</color>
+    <color name="contextual_search_promo_border_color">#C2C2C2</color>
 
     <!-- Progress Bar colors -->
     <color name="progress_bar_foreground">@color/light_active_color</color>
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/OverlayPanel.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/OverlayPanel.java
index deaff7e0..9a031f2 100644
--- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/OverlayPanel.java
+++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/OverlayPanel.java
@@ -84,8 +84,7 @@
         CONTENT_CHANGED,
         KEYBOARD_SHOWN,
         KEYBOARD_HIDDEN,
-        TAB_NAVIGATION,
-        PROMO_ACCEPTED
+        TAB_NAVIGATION
     }
 
     /** The activity this panel is in. */
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/OverlayPanelAnimation.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/OverlayPanelAnimation.java
index 6d99cdc8f..0f088e4 100644
--- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/OverlayPanelAnimation.java
+++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/OverlayPanelAnimation.java
@@ -27,9 +27,7 @@
      * Animation properties.
      */
     protected enum Property {
-        PANEL_HEIGHT,
-        // TODO(pedrosimonetti): Move Promo logic to its own control class.
-        PROMO_VISIBILITY
+        PANEL_HEIGHT
     }
 
     /**
@@ -105,9 +103,6 @@
     // Animation API
     // ============================================================================================
 
-    // TODO(pedrosimonetti): Move Promo logic to its own control class.
-    protected void setPromoVisibilityForOptInAnimation(float percentage) {}
-
     /**
      * Animates the Overlay Panel to its maximized state.
      *
@@ -375,9 +370,6 @@
     public void setProperty(Property prop, float value) {
         if (prop == Property.PANEL_HEIGHT) {
             setPanelHeight(value);
-        } else if (prop == Property.PROMO_VISIBILITY) {
-            // TODO(pedrosimonetti): Move Promo logic to its own control class.
-            setPromoVisibilityForOptInAnimation(value);
         }
     }
 
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/OverlayPanelBase.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/OverlayPanelBase.java
index d645c915..68c346b 100644
--- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/OverlayPanelBase.java
+++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/OverlayPanelBase.java
@@ -312,7 +312,7 @@
      *
      * @return The Panel Bar Container in dps.
      */
-    protected float getBarContainerHeight() {
+    public float getBarContainerHeight() {
         return getBarHeight();
     }
 
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/OverlayPanelInflater.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/OverlayPanelInflater.java
index 873b41ce..2c9bdf3 100644
--- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/OverlayPanelInflater.java
+++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/OverlayPanelInflater.java
@@ -55,13 +55,6 @@
     }
 
     @Override
-    protected void onFinishInflate() {
-        if (!mOverlayPanel.isFullWidthSizePanel()) {
-            invalidate(true);
-        }
-    }
-
-    @Override
     protected int getWidthMeasureSpec() {
         return View.MeasureSpec.makeMeasureSpec(
                 mOverlayPanel.getMaximumWidthPx(), View.MeasureSpec.EXACTLY);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/contextualsearch/ContextualSearchOptOutPromo.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/contextualsearch/ContextualSearchOptOutPromo.java
deleted file mode 100644
index 3accd6da..0000000
--- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/contextualsearch/ContextualSearchOptOutPromo.java
+++ /dev/null
@@ -1,137 +0,0 @@
-// Copyright 2015 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.chrome.browser.compositor.bottombar.contextualsearch;
-
-import android.content.Context;
-import android.text.method.LinkMovementMethod;
-import android.util.AttributeSet;
-import android.view.View;
-import android.widget.Button;
-import android.widget.RelativeLayout;
-import android.widget.TextView;
-
-import org.chromium.chrome.R;
-import org.chromium.ui.resources.dynamics.ViewResourceAdapter;
-import org.chromium.ui.text.NoUnderlineClickableSpan;
-import org.chromium.ui.text.SpanApplier;
-import org.chromium.ui.text.SpanApplier.SpanInfo;
-
-/**
- */
-public class ContextualSearchOptOutPromo extends RelativeLayout {
-    /**
-     * The {@link ViewResourceAdapter} instance.
-     */
-    private ViewResourceAdapter mResourceAdapter;
-
-    /**
-     * The interface used to talk to the Panel.
-     */
-    private ContextualSearchPromoHost mHost;
-
-    /**
-     * The delegate that is used to communicate with the Panel.
-     */
-    public interface ContextualSearchPromoHost {
-        /**
-         * Notifies that the preference link has been clicked.
-         */
-        void onPromoPreferenceClick();
-
-        /**
-         * Notifies that the a button has been clicked.
-         * @param accepted Whether the feature was accepted.
-         */
-        void onPromoButtonClick(boolean accepted);
-    }
-
-    /**
-     * Constructs a new control container.
-     * <p>
-     * This constructor is used when inflating from XML.
-     *
-     * @param context The context used to build this view.
-     * @param attrs The attributes used to determine how to construct this view.
-     */
-    public ContextualSearchOptOutPromo(Context context, AttributeSet attrs) {
-        super(context, attrs);
-    }
-
-    /**
-     * @return The {@link ViewResourceAdapter} that exposes this {@link View} as a CC resource.
-     */
-    public ViewResourceAdapter getResourceAdapter() {
-        return mResourceAdapter;
-    }
-
-    /**
-     * Sets the Promo Host.
-     *
-     * @param host A {@ContextualSearchPromoHost} instance.
-     */
-    public void setPromoHost(ContextualSearchPromoHost host) {
-        mHost = host;
-    }
-
-    @Override
-    public void onFinishInflate() {
-        super.onFinishInflate();
-
-        mResourceAdapter =
-                new ViewResourceAdapter(findViewById(R.id.contextual_search_opt_out_promo));
-
-        // Fill in text with link to Settings.
-        TextView optOutText = (TextView) findViewById(R.id.contextual_search_opt_out_text);
-
-        NoUnderlineClickableSpan settingsLink = new NoUnderlineClickableSpan() {
-            @Override
-            public void onClick(View view) {
-                mHost.onPromoPreferenceClick();
-            }
-        };
-
-        optOutText.setText(SpanApplier.applySpans(
-                getResources().getString(R.string.contextual_search_short_description),
-                new SpanInfo("<link>", "</link>", settingsLink)));
-        optOutText.setMovementMethod(LinkMovementMethod.getInstance());
-
-        // "No thanks" button.
-        Button noThanksButton = (Button) findViewById(R.id.contextual_search_no_thanks_button);
-        noThanksButton.setOnClickListener(new View.OnClickListener() {
-            @Override
-            public void onClick(View v) {
-                mHost.onPromoButtonClick(false);
-            }
-        });
-
-        // "Got it" button.
-        Button gotItButton = (Button) findViewById(R.id.contextual_search_got_it_button);
-        gotItButton.setOnClickListener(new View.OnClickListener() {
-            @Override
-            public void onClick(View v) {
-                mHost.onPromoButtonClick(true);
-            }
-        });
-
-        setVisibility(View.INVISIBLE);
-    }
-
-    /**
-     * Gets the Promo height for the given width.
-     *
-     * @param width The given width.
-     * @return The Promo height for the given width.
-     */
-    public int getHeightForGivenWidth(int width) {
-        // The Promo will be as wide as possible (same width as the Panel).
-        int widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
-        // But the height will depend on how big is the Promo text.
-        int heightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
-        // Calculates the height.
-        measure(widthMeasureSpec, heightMeasureSpec);
-
-        return getMeasuredHeight();
-    }
-}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/contextualsearch/ContextualSearchPanel.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/contextualsearch/ContextualSearchPanel.java
index 5c953da..fa24c6b 100644
--- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/contextualsearch/ContextualSearchPanel.java
+++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/contextualsearch/ContextualSearchPanel.java
@@ -7,10 +7,9 @@
 import android.app.Activity;
 import android.content.Context;
 import android.os.Handler;
-import android.view.LayoutInflater;
-import android.view.View;
 
 import org.chromium.base.ActivityState;
+import org.chromium.base.ApiCompatibilityUtils;
 import org.chromium.base.VisibleForTesting;
 import org.chromium.chrome.R;
 import org.chromium.chrome.browser.compositor.bottombar.OverlayContentProgressObserver;
@@ -18,22 +17,18 @@
 import org.chromium.chrome.browser.compositor.bottombar.OverlayPanelContent;
 import org.chromium.chrome.browser.compositor.bottombar.OverlayPanelManager;
 import org.chromium.chrome.browser.compositor.bottombar.OverlayPanelManager.PanelPriority;
+import org.chromium.chrome.browser.compositor.bottombar.contextualsearch.ContextualSearchPromoControl.ContextualSearchPromoHost;
 import org.chromium.chrome.browser.compositor.layouts.LayoutUpdateHost;
 import org.chromium.chrome.browser.compositor.scene_layer.ContextualSearchSceneLayer;
 import org.chromium.chrome.browser.compositor.scene_layer.SceneLayer;
 import org.chromium.chrome.browser.contextualsearch.ContextualSearchManagementDelegate;
-import org.chromium.chrome.browser.preferences.PrefServiceBridge;
-import org.chromium.chrome.browser.preferences.PreferencesLauncher;
-import org.chromium.chrome.browser.preferences.privacy.ContextualSearchPreferenceFragment;
 import org.chromium.chrome.browser.util.MathUtils;
-import org.chromium.ui.base.LocalizationUtils;
 import org.chromium.ui.resources.ResourceManager;
 
 /**
  * Controls the Contextual Search Panel.
  */
-public class ContextualSearchPanel extends OverlayPanel
-        implements ContextualSearchOptOutPromo.ContextualSearchPromoHost {
+public class ContextualSearchPanel extends OverlayPanel {
 
     /**
      * The delay after which the hide progress will be hidden.
@@ -41,16 +36,21 @@
     private static final long HIDE_PROGRESS_BAR_DELAY = 1000 / 60 * 4;
 
     /**
-     * Whether the Panel should be promoted to a new tab after being maximized.
-     */
-    private boolean mShouldPromoteToTabAfterMaximizing;
-
-    /**
      * Used for logging state changes.
      */
     private final ContextualSearchPanelMetrics mPanelMetrics;
 
     /**
+     * The height of the bar shadow, in pixels.
+     */
+    private final float mBarShadowHeightPx;
+
+    /**
+     * Whether the Panel should be promoted to a new tab after being maximized.
+     */
+    private boolean mShouldPromoteToTabAfterMaximizing;
+
+    /**
      * The object for handling global Contextual Search management duties
      */
     private ContextualSearchManagementDelegate mManagementDelegate;
@@ -77,8 +77,12 @@
     public ContextualSearchPanel(Context context, LayoutUpdateHost updateHost,
                 OverlayPanelManager panelManager) {
         super(context, updateHost, panelManager);
+
         mSceneLayer = createNewContextualSearchSceneLayer();
         mPanelMetrics = new ContextualSearchPanelMetrics();
+
+        mBarShadowHeightPx = ApiCompatibilityUtils.getDrawable(mContext.getResources(),
+                R.drawable.contextual_search_bar_shadow).getIntrinsicHeight();
     }
 
     @Override
@@ -135,6 +139,7 @@
         mSceneLayer.update(resourceManager, this,
                 getSearchBarControl(),
                 getPeekPromoControl(),
+                getPromoControl(),
                 getIconSpriteControl());
     }
 
@@ -162,6 +167,16 @@
         }
     }
 
+    /**
+     * Notifies that the preference state has changed.
+     * @param isEnabled Whether the feature is enabled.
+     */
+    public void onContextualSearchPrefChanged(boolean isEnabled) {
+        if (!isShowing()) return;
+
+        getPromoControl().onContextualSearchPrefChanged(isEnabled);
+    }
+
     // ============================================================================================
     // Panel State
     // ============================================================================================
@@ -190,10 +205,6 @@
             }
         }
 
-        if (toState == PanelState.EXPANDED) {
-            showPromoViewAtYPosition(getPromoYPx());
-        }
-
         if (fromState == PanelState.PEEKED
                 && (toState == PanelState.EXPANDED || toState == PanelState.MAXIMIZED)) {
             // After opening the Panel to either expanded or maximized state,
@@ -212,24 +223,30 @@
         if (canDisplayContentInPanel()) {
             return super.getExpandedHeight();
         } else {
-            return getBarHeightPeeking() + mPromoContentHeightPx * mPxToDp;
+            return getBarHeightPeeking() + getPromoHeightPx() * mPxToDp;
         }
     }
 
+    @Override
+    protected PanelState getProjectedState(float velocity) {
+        PanelState projectedState = super.getProjectedState(velocity);
+
+        // Prevent the fling gesture from moving the Panel from PEEKED to MAXIMIZED. This is to
+        // make sure the Promo will be visible, considering that the EXPANDED state is the only
+        // one that will show the Promo.
+        if (getPromoControl().isVisible()
+                && projectedState == PanelState.MAXIMIZED
+                && getPanelState() == PanelState.PEEKED) {
+            projectedState = PanelState.EXPANDED;
+        }
+
+        return projectedState;
+    }
+
     // ============================================================================================
     // Contextual Search Manager Integration
     // ============================================================================================
 
-    /**
-     * @param enabled Whether the preference should be enabled.
-     */
-    public void setPreferenceState(boolean enabled) {
-        if (mManagementDelegate != null) {
-            PrefServiceBridge.getInstance().setContextualSearchState(enabled);
-            setIsPromoActive(false, false);
-        }
-    }
-
     @Override
     protected void onClosed(StateChangeReason reason) {
         // Must be called before destroying Content because unseen visits should be removed from
@@ -286,7 +303,7 @@
     @Override
     protected void destroyComponents() {
         super.destroyComponents();
-        destroyPromoView();
+        destroyPromoControl();
         destroyPeekPromoControl();
         destroySearchBarControl();
     }
@@ -323,6 +340,32 @@
         }
     }
 
+    @Override
+    public float getContentY() {
+        return getOffsetY() + getBarContainerHeight() + getPromoHeightPx() * mPxToDp;
+    }
+
+    @Override
+    public float getBarContainerHeight() {
+        return getBarHeight() + getPeekPromoControl().getHeightPx();
+    }
+
+    @Override
+    protected float getPeekedHeight() {
+        return getBarHeightPeeking() + getPeekPromoControl().getHeightPeekingPx() * mPxToDp;
+    }
+
+    @Override
+    protected float calculateBarShadowOpacity() {
+        float barShadowOpacity = 0.f;
+        if (getPromoHeightPx() > 0.f) {
+            float threshold = 2 * mBarShadowHeightPx;
+            barShadowOpacity = getPromoHeightPx() > mBarShadowHeightPx ? 1.f
+                    : MathUtils.interpolate(0.f, 1.f, getPromoHeightPx() / threshold);
+        }
+        return barShadowOpacity;
+    }
+
     // ============================================================================================
     // Animation Handling
     // ============================================================================================
@@ -331,11 +374,6 @@
     protected void onAnimationFinished() {
         super.onAnimationFinished();
 
-        if (mIsAnimatingPromoAcceptance) {
-            mIsAnimatingPromoAcceptance = false;
-            onPromoAcceptanceAnimationFinished();
-        }
-
         if (mShouldPromoteToTabAfterMaximizing && getPanelState() == PanelState.MAXIMIZED) {
             mShouldPromoteToTabAfterMaximizing = false;
             mManagementDelegate.promoteToTab();
@@ -357,8 +395,12 @@
      * @param isActive Whether the promo is active.
      */
     public void setIsPromoActive(boolean isActive, boolean isMandatory) {
-        mIsPromoMandatory = isMandatory;
-        setPromoVisibility(isActive);
+        if (isActive) {
+            getPromoControl().show(isMandatory);
+        } else {
+            getPromoControl().hide();
+        }
+
         mPanelMetrics.setIsPromoActive(isActive);
     }
 
@@ -501,8 +543,7 @@
     protected void updatePanelForCloseOrPeek(float percentage) {
         super.updatePanelForCloseOrPeek(percentage);
 
-        // Update the opt out promo.
-        updatePromoVisibility(1.f);
+        getPromoControl().onUpdateFromCloseToPeek(percentage);
 
         getPeekPromoControl().onUpdateFromCloseToPeek(percentage);
         getSearchBarControl().onUpdateFromCloseToPeek(percentage);
@@ -512,8 +553,7 @@
     protected void updatePanelForExpansion(float percentage) {
         super.updatePanelForExpansion(percentage);
 
-        // Update the opt out promo.
-        updatePromoVisibility(1.f);
+        getPromoControl().onUpdateFromPeekToExpand(percentage);
 
         getPeekPromoControl().onUpdateFromPeekToExpand(percentage);
         getSearchBarControl().onUpdateFromPeekToExpand(percentage);
@@ -523,8 +563,7 @@
     protected void updatePanelForMaximization(float percentage) {
         super.updatePanelForMaximization(percentage);
 
-        // Update the opt out promo.
-        updatePromoVisibility(1.f - percentage);
+        getPromoControl().onUpdateFromExpandToMaximize(percentage);
 
         getPeekPromoControl().onUpdateFromExpandToMaximize(percentage);
         getSearchBarControl().onUpdateFromExpandToMaximize(percentage);
@@ -532,8 +571,8 @@
 
     @Override
     protected void updatePanelForOrientationChange() {
-        if (isPromoVisible()) {
-            updatePromoLayout();
+        if (getPromoControl().isVisible()) {
+            getPromoControl().invalidate(true);
         }
 
         // NOTE(pedrosimonetti): We cannot tell where the selection will be after the
@@ -586,14 +625,10 @@
      * they won't actually be displayed on the screen (their snapshots will be displayed instead).
      */
     protected ContextualSearchBarControl getSearchBarControl() {
-        assert mContainerView != null;
-        assert mResourceLoader != null;
-
         if (mSearchBarControl == null) {
             mSearchBarControl =
                     new ContextualSearchBarControl(this, mContext, mContainerView, mResourceLoader);
         }
-
         return mSearchBarControl;
     }
 
@@ -641,32 +676,14 @@
     private ContextualSearchPeekPromoControl mPeekPromoControl;
 
     /**
-     * @return The height of the Peek Promo in the peeked state, in pixels.
-     */
-    protected float getPeekPromoHeightPeekingPx() {
-        return getPeekPromoControl().getHeightPeekingPx();
-    }
-
-    /**
-     * @return The height of the Peek Promo, in pixels.
-     */
-    protected float getPeekPromoHeight() {
-        return getPeekPromoControl().getHeightPx();
-    }
-
-    /**
      * Creates the ContextualSearchPeekPromoControl, if needed.
      */
     private ContextualSearchPeekPromoControl getPeekPromoControl() {
-        assert mContainerView != null;
-        assert mResourceLoader != null;
-
         if (mPeekPromoControl == null) {
             mPeekPromoControl =
                     new ContextualSearchPeekPromoControl(this, mContext, mContainerView,
                             mResourceLoader);
         }
-
         return mPeekPromoControl;
     }
 
@@ -684,51 +701,65 @@
     // Promo
     // ============================================================================================
 
-    // TODO(pedrosimonetti): refactor the rest of the promo code into its own Control.
+    private ContextualSearchPromoControl mPromoControl;
+    private ContextualSearchPromoHost mPromoHost;
 
     /**
-     * Whether the Promo is visible.
+     * @return Height of the promo in pixels.
      */
-    private boolean mIsPromoVisible;
-
-    /**
-     * Whether the Promo is mandatory.
-     */
-    private boolean mIsPromoMandatory;
-
-    /**
-     * Whether Mandatory Promo acceptance is being animated.
-     */
-    private boolean mIsAnimatingMandatoryPromoAcceptance;
-
-    /**
-     * @return Whether the Panel Promo is visible.
-     */
-    protected boolean isPromoVisible() {
-        return mIsPromoVisible;
+    private float getPromoHeightPx() {
+        return getPromoControl().getHeightPx();
     }
 
     /**
-     * Notifies that the acceptance animation has finished.
+     * Creates the ContextualSearchPromoControl, if needed.
      */
-    protected void onPromoAcceptanceAnimationFinished() {
-        mIsAnimatingMandatoryPromoAcceptance = false;
-
-        // NOTE(pedrosimonetti): We should only set the preference to true after the acceptance
-        // animation finishes, because setting the preference will make the user leave the
-        // undecided state, and that will, in turn, turn the promo off.
-        setPreferenceState(true);
-    }
-
-    /**
-     * @param isVisible Whether the Promo should be visible.
-     */
-    private void setPromoVisibility(boolean isVisible) {
-        mIsPromoVisible = isVisible;
-
-        if (mIsPromoVisible) {
-            createPromoView();
+    private ContextualSearchPromoControl getPromoControl() {
+        if (mPromoControl == null) {
+            mPromoControl =
+                    new ContextualSearchPromoControl(this, getContextualSearchPromoHost(),
+                            mContext, mContainerView, mResourceLoader);
         }
+        return mPromoControl;
+    }
+
+    /**
+     * Destroys the ContextualSearchPromoControl.
+     */
+    private void destroyPromoControl() {
+        if (mPromoControl != null) {
+            mPromoControl.destroy();
+            mPromoControl = null;
+        }
+    }
+
+    /**
+     * @return An implementation of {@link ContextualSearchPromoHost}.
+     */
+    private ContextualSearchPromoHost getContextualSearchPromoHost() {
+        if (mPromoHost == null) {
+            mPromoHost = new ContextualSearchPromoHost() {
+                @Override
+                public void onPromoOptIn(boolean wasMandatory) {
+                    if (wasMandatory) {
+                        getOverlayPanelContent().showContent();
+                        expandPanel(StateChangeReason.OPTIN);
+                    }
+                }
+
+                @Override
+                public void onPromoOptOut() {
+                    closePanel(OverlayPanel.StateChangeReason.OPTOUT, true);
+                }
+
+                @Override
+                public void onUpdatePromoAppearance() {
+                    ContextualSearchPanel.this.updateBarShadow();
+                }
+            };
+        }
+
+        return mPromoHost;
     }
 
     // ============================================================================================
@@ -740,7 +771,7 @@
      */
     public boolean canDisplayContentInPanel() {
         // TODO(pedrosimonetti): add svelte support.
-        return !mIsPromoMandatory || mIsAnimatingMandatoryPromoAcceptance;
+        return !getPromoControl().isMandatory();
     }
 
     @Override
@@ -756,315 +787,4 @@
     public void destroyContent() {
         super.destroyOverlayPanelContent();
     }
-
-    // ============================================================================================
-    // Promo Host
-    // ============================================================================================
-
-    @Override
-    public void onPromoPreferenceClick() {
-        new Handler().post(new Runnable() {
-            @Override
-            public void run() {
-                PreferencesLauncher.launchSettingsPage(mContext,
-                        ContextualSearchPreferenceFragment.class.getName());
-            }
-        });
-    }
-
-    @Override
-    public void onPromoButtonClick(boolean accepted) {
-        if (accepted) {
-            animatePromoAcceptance();
-        } else {
-            hidePromoView();
-            // NOTE(pedrosimonetti): If the user has opted out of Contextual Search, we should set
-            // the preference right away because the preference state controls whether the promo
-            // will be visible, and we want to hide the promo immediately when the user opts out.
-            setPreferenceState(false);
-            closePanel(StateChangeReason.OPTOUT, true);
-        }
-    }
-
-    // ============================================================================================
-    // Opt Out Promo View
-    // ============================================================================================
-
-    // TODO(pedrosimonetti): Consider maybe adding a 9.patch to avoid the hacky nested layouts in
-    // order to have the transparent gap at the top of the Promo View. Currently, the Promo View
-    // has a gap at the top where a shadow will be rendered. The gap is needed because the shadow
-    // needs to be rendered with the Compositor, which cannot be rendered on top of the Promo's
-    // Android View. The suggestion here is to try to use a 9.patch to render the background of
-    // the Promo View, which would include the gap at the top. This would allow us simplify the
-    // Promo View, by removing the extra nested layout used to leave a gap at the top of the View.
-
-    /**
-     * The {@link ContextualSearchOptOutPromo} instance.
-     */
-    private ContextualSearchOptOutPromo mPromoView;
-
-    /**
-     * Whether the Search Promo View is visible.
-     */
-    private boolean mIsSearchPromoViewVisible = false;
-
-    /**
-     * Whether the Promo's acceptance animation is running.
-     */
-    private boolean mIsAnimatingPromoAcceptance;
-
-    /**
-     * The Y position of the Search Promo.
-     */
-    private float mSearchPromoY;
-
-    /**
-     * Creates the Search Promo View.
-     */
-    protected void createPromoView() {
-        if (isPromoVisible() && mPromoView == null) {
-            assert mContainerView != null;
-
-            // TODO(pedrosimonetti): Refactor promo code to use ViewResourceInflater.
-            LayoutInflater.from(mContext).inflate(
-                    R.layout.contextual_search_opt_out_promo, mContainerView);
-            mPromoView = (ContextualSearchOptOutPromo)
-                    mContainerView.findViewById(R.id.contextual_search_opt_out_promo);
-
-            if (mResourceLoader != null) {
-                mResourceLoader.registerResource(R.id.contextual_search_opt_out_promo,
-                        mPromoView.getResourceAdapter());
-            }
-
-            mPromoView.setPromoHost(this);
-
-            updatePromoLayout();
-
-            assert mPromoView != null;
-        }
-    }
-
-    /**
-     * Updates the Promo layout.
-     */
-    protected void updatePromoLayout() {
-        final int maximumWidth = getMaximumWidthPx();
-
-        // Adjust size for small Panel.
-        if (!isFullWidthSizePanel()) {
-            mPromoView.getLayoutParams().width = maximumWidth;
-            mPromoView.requestLayout();
-        }
-
-        setPromoContentHeightPx(mPromoView.getHeightForGivenWidth(maximumWidth));
-    }
-
-    /**
-     * Destroys the Search Promo View.
-     */
-    protected void destroyPromoView() {
-        if (mPromoView != null) {
-            mContainerView.removeView(mPromoView);
-            mPromoView = null;
-            if (mResourceLoader != null) {
-                mResourceLoader.unregisterResource(R.id.contextual_search_opt_out_promo);
-            }
-        }
-    }
-
-    /**
-     * Displays the Search Promo View at the given Y position.
-     *
-     * @param y The Y position.
-     */
-    private void showPromoViewAtYPosition(float y) {
-        if (mPromoView == null
-                || mIsAnimatingMandatoryPromoAcceptance
-                || !isPromoVisible()
-                || (mIsSearchPromoViewVisible && mSearchPromoY == y)) return;
-
-        float offsetX = getOffsetX() / mPxToDp;
-        if (LocalizationUtils.isLayoutRtl()) {
-            offsetX = -offsetX;
-        }
-
-        mPromoView.setTranslationX(offsetX);
-        mPromoView.setTranslationY(y);
-        mPromoView.setVisibility(View.VISIBLE);
-
-        // NOTE(pedrosimonetti): We need to call requestLayout, otherwise
-        // the Promo View will not become visible.
-        mPromoView.requestLayout();
-
-        mIsSearchPromoViewVisible = true;
-        mSearchPromoY = y;
-    }
-
-    /**
-     * Hides the Search Promo View.
-     */
-    protected void hidePromoView() {
-        if (mPromoView == null
-                || !mIsSearchPromoViewVisible
-                || !isPromoVisible()) {
-            return;
-        }
-
-        mPromoView.setVisibility(View.INVISIBLE);
-
-        mIsSearchPromoViewVisible = false;
-    }
-
-    /**
-     * Animates the acceptance of the Promo.
-     */
-    protected void animatePromoAcceptance() {
-        hidePromoView();
-
-        if (mIsPromoMandatory) {
-            mIsAnimatingMandatoryPromoAcceptance = true;
-            getOverlayPanelContent().showContent();
-            expandPanel(StateChangeReason.PROMO_ACCEPTED);
-        }
-
-        mIsAnimatingPromoAcceptance = true;
-        animateProperty(Property.PROMO_VISIBILITY, 1.f, 0.f, BASE_ANIMATION_DURATION_MS);
-    }
-
-    /**
-     * Updates the UI state for Opt In Promo animation.
-     *
-     * @param percentage The visibility percentage of the Promo.
-     */
-    @Override
-    protected void setPromoVisibilityForOptInAnimation(float percentage) {
-        updatePromoVisibility(percentage);
-        updateBarShadow();
-    }
-
-    /**
-     * Updates the UI state for Opt Out Promo.
-     *
-     * @param percentage The visibility percentage of the Promo. A visibility of 0 means the
-     * Promo is not visible. A visibility of 1 means the Promo is fully visible. And
-     * visibility between 0 and 1 means the Promo is partially visible.
-     */
-    private void updatePromoVisibility(float percentage) {
-        if (isPromoVisible()) {
-            mPromoVisible = true;
-
-            mPromoHeightPx = Math.round(MathUtils.clamp(percentage * mPromoContentHeightPx,
-                    0.f, mPromoContentHeightPx));
-            mPromoOpacity = percentage;
-        } else {
-            mPromoVisible = false;
-            mPromoHeightPx = 0.f;
-            mPromoOpacity = 0.f;
-        }
-    }
-
-    // --------------------------------------------------------------------------------------------
-    // Promo states
-    // --------------------------------------------------------------------------------------------
-
-    private boolean mPromoVisible = false;
-    private float mPromoContentHeightPx = 0.f;
-    private float mPromoHeightPx;
-    private float mPromoOpacity;
-
-    /**
-     * @return Whether the promo is visible.
-     */
-    public boolean getPromoVisible() {
-        return mPromoVisible;
-    }
-
-    /**
-     * Sets the height of the promo content.
-     */
-    public void setPromoContentHeightPx(float heightPx) {
-        mPromoContentHeightPx = heightPx;
-    }
-
-    /**
-     * @return Height of the promo in pixels.
-     */
-    public float getPromoHeightPx() {
-        return mPromoHeightPx;
-    }
-
-    /**
-     * @return The opacity of the promo.
-     */
-    public float getPromoOpacity() {
-        return mPromoOpacity;
-    }
-
-    /**
-     * @return Y coordinate of the promo in pixels.
-     */
-    protected float getPromoYPx() {
-        return Math.round((getOffsetY() + getBarContainerHeight()) / mPxToDp);
-    }
-
-    // ============================================================================================
-    // Changes made to the OverlayPanel methods in order to support the Promo.
-    // TODO(pedrosimonetti): Re-organize this code once Promo is implemented in its own Control.
-    // ============================================================================================
-
-    @Override
-    protected void setPanelHeight(float height) {
-        // As soon as we resize the Panel to a different height than the expanded one,
-        // then we should hide the Promo View once the snapshot will be shown in its place.
-        if (height != getPanelHeightFromState(PanelState.EXPANDED)) {
-            hidePromoView();
-        }
-
-        super.setPanelHeight(height);
-    }
-
-    @Override
-    protected PanelState getProjectedState(float velocity) {
-        PanelState projectedState = super.getProjectedState(velocity);
-
-        // Prevent the fling gesture from moving the Panel from PEEKED to MAXIMIZED if the Panel
-        // Promo is available and we are running in full screen panel mode. This is to make sure
-        // the Promo will be visible, considering that the EXPANDED state is the only one that will
-        // show the Promo in full screen panel mode. In narrow panel UI the Promo is visible in
-        // maximized so this project state change is not needed.
-        if (isPromoVisible()
-                && projectedState == PanelState.MAXIMIZED
-                && getPanelState() == PanelState.PEEKED) {
-            projectedState = PanelState.EXPANDED;
-        }
-
-        return projectedState;
-    }
-
-    @Override
-    public float getContentY() {
-        return getOffsetY() + getBarContainerHeight() + getPromoHeightPx() * mPxToDp;
-    }
-
-    @Override
-    protected float getBarContainerHeight() {
-        return getBarHeight() + getPeekPromoHeight();
-    }
-
-    @Override
-    protected float getPeekedHeight() {
-        return getBarHeightPeeking() + getPeekPromoHeightPeekingPx() * mPxToDp;
-    }
-
-    @Override
-    protected float calculateBarShadowOpacity() {
-        float barShadowOpacity = 0.f;
-        float barShadowHeightPx = 9.f / mPxToDp;
-        if (getPromoHeightPx() > 0.f) {
-            float threshold = 2 * barShadowHeightPx;
-            barShadowOpacity = getPromoHeightPx() > barShadowHeightPx ? 1.f
-                    : MathUtils.interpolate(0.f, 1.f, getPromoHeightPx() / threshold);
-        }
-        return barShadowOpacity;
-    }
 }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/contextualsearch/ContextualSearchPromoControl.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/contextualsearch/ContextualSearchPromoControl.java
new file mode 100644
index 0000000..16ae169
--- /dev/null
+++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/contextualsearch/ContextualSearchPromoControl.java
@@ -0,0 +1,489 @@
+// Copyright 2015 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.chrome.browser.compositor.bottombar.contextualsearch;
+
+import android.content.Context;
+import android.os.Handler;
+import android.text.method.LinkMovementMethod;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.Button;
+import android.widget.TextView;
+
+import org.chromium.chrome.R;
+import org.chromium.chrome.browser.compositor.bottombar.OverlayPanel;
+import org.chromium.chrome.browser.compositor.bottombar.OverlayPanelAnimation;
+import org.chromium.chrome.browser.compositor.bottombar.OverlayPanelInflater;
+import org.chromium.chrome.browser.compositor.layouts.ChromeAnimation;
+import org.chromium.chrome.browser.preferences.PrefServiceBridge;
+import org.chromium.chrome.browser.preferences.PreferencesLauncher;
+import org.chromium.chrome.browser.preferences.privacy.ContextualSearchPreferenceFragment;
+import org.chromium.chrome.browser.util.MathUtils;
+import org.chromium.ui.base.LocalizationUtils;
+import org.chromium.ui.resources.dynamics.DynamicResourceLoader;
+import org.chromium.ui.text.NoUnderlineClickableSpan;
+import org.chromium.ui.text.SpanApplier;
+
+/**
+ * Controls the Search Promo.
+ */
+public class ContextualSearchPromoControl extends OverlayPanelInflater
+        implements ChromeAnimation.Animatable<ContextualSearchPromoControl.AnimationType> {
+
+    /**
+     * Animation types.
+     */
+    protected enum AnimationType {
+        COLLAPSE
+    }
+
+    /**
+     * The pixel density.
+     */
+    private final float mDpToPx;
+
+    /**
+     * Whether the Promo is visible.
+     */
+    private boolean mIsVisible;
+
+    /**
+     * Whether the Promo is mandatory.
+     */
+    private boolean mIsMandatory;
+
+    /**
+     * The opacity of the Promo.
+     */
+    private float mOpacity;
+
+    /**
+     * The height of the Promo in pixels.
+     */
+    private float mHeightPx;
+
+    /**
+     * The height of the Promo content in pixels.
+     */
+    private float mContentHeightPx;
+
+    /**
+     * Whether the Promo View is showing.
+     */
+    private boolean mIsShowingView;
+
+    /**
+     * The Y position of the Promo View.
+     */
+    private float mPromoViewY;
+
+    /**
+     * Whether the user's choice has been handled.
+     */
+    private boolean mHasHandledChoice;
+
+    /**
+     * The interface used to talk to the Panel.
+     */
+    private ContextualSearchPromoHost mHost;
+
+    /**
+     * The delegate that is used to communicate with the Panel.
+     */
+    public interface ContextualSearchPromoHost {
+        /**
+         * Notifies that the user has opted in.
+         * @param wasMandatory Whether the Promo was mandatory.
+         */
+        void onPromoOptIn(boolean wasMandatory);
+
+        /**
+         * Notifies that the user has opted out.
+         */
+        void onPromoOptOut();
+
+        /**
+         * Notifies that the Promo appearance has changed.
+         */
+        void onUpdatePromoAppearance();
+    }
+
+    /**
+     * @param panel             The panel.
+     * @param context           The Android Context used to inflate the View.
+     * @param container         The container View used to inflate the View.
+     * @param resourceLoader    The resource loader that will handle the snapshot capturing.
+     */
+    public ContextualSearchPromoControl(OverlayPanel panel,
+                                        ContextualSearchPromoHost host,
+                                        Context context,
+                                        ViewGroup container,
+                                        DynamicResourceLoader resourceLoader) {
+        super(panel, R.layout.contextual_search_promo_view,
+                R.id.contextual_search_promo, context, container, resourceLoader);
+
+        mDpToPx = context.getResources().getDisplayMetrics().density;
+
+        mHost = host;
+    }
+
+    // ============================================================================================
+    // Public API
+    // ============================================================================================
+
+    /**
+     * Shows the Promo. This includes inflating the View and setting its initial state.
+     * @param isMandatory Whether the Promo is mandatory.
+     */
+    public void show(boolean isMandatory) {
+        if (mIsVisible) return;
+
+        // Invalidates the View in order to generate a snapshot, but do not show the View yet.
+        // The View should only be displayed when in the expanded state.
+        invalidate();
+
+        mIsVisible = true;
+        mIsMandatory = isMandatory;
+        mHeightPx = mContentHeightPx;
+    }
+
+    /**
+     * Hides the Promo
+     */
+    public void hide() {
+        if (!mIsVisible) return;
+
+        hidePromoView();
+
+        mIsVisible = false;
+        mIsMandatory = false;
+
+        mHeightPx = 0.f;
+        mOpacity = 0.f;
+    }
+
+    /**
+     * Handles change in the Contextual Search preference state.
+     * @param isEnabled Whether the feature was enable.
+     */
+    public void onContextualSearchPrefChanged(boolean isEnabled) {
+        if (!mIsVisible || !mOverlayPanel.isShowing()) return;
+
+        if (isEnabled) {
+            boolean wasMandatory = mIsMandatory;
+            // Set mandatory state to false right now because it controls whether the Content
+            // can be displayed. See {@link ContextualSearchPanel#canDisplayContentInPanel}.
+            // Now that the feature is enable, the host will try to show the Contents.
+            // See {@link ContextualSearchPanel#getContextualSearchPromoHost}.
+            mIsMandatory = false;
+            mHost.onPromoOptIn(wasMandatory);
+        } else {
+            mHost.onPromoOptOut();
+        }
+
+        collapse();
+    }
+
+    /**
+     * @return Whether the Promo is visible.
+     */
+    public boolean isVisible() {
+        return mIsVisible;
+    }
+
+    /**
+     * @return Whether the Promo is mandatory.
+     */
+    public boolean isMandatory() {
+        return mIsMandatory;
+    }
+
+    /**
+     * @return The Promo height in pixels.
+     */
+    public float getHeightPx() {
+        return mHeightPx;
+    }
+
+    /**
+     * @return The Promo opacity.
+     */
+    public float getOpacity() {
+        return mOpacity;
+    }
+
+    // ============================================================================================
+    // Panel Animation
+    // ============================================================================================
+
+    /**
+     * Interpolates the UI from states Closed to Peeked.
+     *
+     * @param percentage The completion percentage.
+     */
+    public void onUpdateFromCloseToPeek(float percentage) {
+        if (!isVisible()) return;
+
+        // Promo snapshot should be fully visible here.
+        updateAppearance(1.f);
+
+        // The View should not be visible in this state.
+        hidePromoView();
+    }
+
+    /**
+     * Interpolates the UI from states Peeked to Expanded.
+     *
+     * @param percentage The completion percentage.
+     */
+    public void onUpdateFromPeekToExpand(float percentage) {
+        if (!isVisible()) return;
+
+        // Promo snapshot should be fully visible here.
+        updateAppearance(1.f);
+
+        if (percentage == 1.f) {
+            // We should show the Promo View only when the Panel
+            // has reached the exact expanded height.
+            showPromoView();
+        } else {
+            // Otherwise the View should not be visible.
+            hidePromoView();
+        }
+    }
+
+    /**
+     * Interpolates the UI from states Expanded to Maximized.
+     *
+     * @param percentage The completion percentage.
+     */
+    public void onUpdateFromExpandToMaximize(float percentage) {
+        if (!isVisible()) return;
+
+        // Promo snapshot collapses as the Panel reaches the maximized state.
+        updateAppearance(1.f - percentage);
+
+        // The View should not be visible in this state.
+        hidePromoView();
+    }
+
+    // ============================================================================================
+    // Promo Acceptance Animation
+    // ============================================================================================
+
+    @Override
+    public void setProperty(AnimationType type, float value) {
+        if (type == AnimationType.COLLAPSE) {
+            updateAppearance(value);
+        }
+    }
+
+    @Override
+    public void onPropertyAnimationFinished(AnimationType type) {
+        if (type == AnimationType.COLLAPSE) {
+            hide();
+        }
+    }
+
+    /**
+     * Collapses the Promo in an animated fashion.
+     */
+    public void collapse() {
+        hidePromoView();
+
+        mOverlayPanel.addToAnimation(this, AnimationType.COLLAPSE, 1.f, 0.f,
+                OverlayPanelAnimation.BASE_ANIMATION_DURATION_MS, 0);
+    }
+
+    /**
+     * Updates the appearance of the Promo.
+     *
+     * @param percentage The completion percentage. 0.f means the Promo is fully collapsed and
+     *                   transparent. 1.f means the Promo is fully expanded and opaque.
+     */
+    private void updateAppearance(float percentage) {
+        if (mIsVisible) {
+            mHeightPx = Math.round(MathUtils.clamp(percentage * mContentHeightPx,
+                    0.f, mContentHeightPx));
+            mOpacity = percentage;
+        } else {
+            mHeightPx = 0.f;
+            mOpacity = 0.f;
+        }
+
+        mHost.onUpdatePromoAppearance();
+    }
+
+    // ============================================================================================
+    // Custom Behaviors
+    // ============================================================================================
+
+    @Override
+    public void destroy() {
+        hide();
+        super.destroy();
+    }
+
+    @Override
+    public void invalidate(boolean didViewSizeChange) {
+        super.invalidate(didViewSizeChange);
+
+        if (didViewSizeChange) {
+            calculatePromoHeight();
+        }
+    }
+
+    @Override
+    protected void onFinishInflate() {
+        super.onFinishInflate();
+
+        View view = getView();
+
+        // "Allow" button.
+        Button allowButton = (Button) view.findViewById(R.id.contextual_search_allow_button);
+        allowButton.setOnClickListener(new View.OnClickListener() {
+            @Override
+            public void onClick(View v) {
+                ContextualSearchPromoControl.this.handlePromoChoice(true);
+            }
+        });
+
+        // "No thanks" button.
+        Button noThanksButton = (Button) view.findViewById(R.id.contextual_search_no_thanks_button);
+        noThanksButton.setOnClickListener(new View.OnClickListener() {
+            @Override
+            public void onClick(View v) {
+                ContextualSearchPromoControl.this.handlePromoChoice(false);
+            }
+        });
+
+        // Fill in text with link to Settings.
+        TextView promoText = (TextView) view.findViewById(R.id.contextual_search_promo_text);
+
+        NoUnderlineClickableSpan settingsLink = new NoUnderlineClickableSpan() {
+            @Override
+            public void onClick(View view) {
+                ContextualSearchPromoControl.this.handleClickSettingsLink();
+            }
+        };
+
+        promoText.setText(SpanApplier.applySpans(
+                view.getResources().getString(R.string.contextual_search_short_description),
+                new SpanApplier.SpanInfo("<link>", "</link>", settingsLink)));
+        promoText.setMovementMethod(LinkMovementMethod.getInstance());
+
+        calculatePromoHeight();
+    }
+
+    @Override
+    protected boolean shouldDetachViewAfterCapturing() {
+        return false;
+    }
+
+    // ============================================================================================
+    // Promo Interaction
+    // ============================================================================================
+
+    /**
+     * Handles the choice made by the user in the Promo.
+     * @param hasEnabled Whether the user has chosen to enable the feature.
+     */
+    private void handlePromoChoice(boolean hasEnabled) {
+        if (!mHasHandledChoice) {
+            mHasHandledChoice = true;
+            PrefServiceBridge.getInstance().setContextualSearchState(hasEnabled);
+        }
+    }
+
+    /**
+     * Handles a click in the settings link located in the Promo.
+     */
+    private void handleClickSettingsLink() {
+        new Handler().post(new Runnable() {
+            @Override
+            public void run() {
+                PreferencesLauncher.launchSettingsPage(getContext(),
+                        ContextualSearchPreferenceFragment.class.getName());
+            }
+        });
+    }
+
+    // ============================================================================================
+    // Helpers
+    // ============================================================================================
+
+    /**
+     * Shows the Promo Android View. By making the Android View visible, we are allowing the
+     * Promo to be interactive. Since snapshots are not interactive (they are just a bitmap),
+     * we need to temporarily show the Android View on top of the snapshot, so the user will
+     * be able to click in the Promo buttons and/or link.
+     */
+    private void showPromoView() {
+        float y = getYPx();
+        View view = getView();
+        if (view == null
+                || !mIsVisible
+                || (mIsShowingView && mPromoViewY == y)) return;
+
+        float offsetX = mOverlayPanel.getOffsetX() * mDpToPx;
+        if (LocalizationUtils.isLayoutRtl()) {
+            offsetX = -offsetX;
+        }
+
+        view.setTranslationX(offsetX);
+        view.setTranslationY(y);
+        view.setVisibility(View.VISIBLE);
+
+        // NOTE(pedrosimonetti): We need to call requestLayout, otherwise
+        // the Promo View will not become visible.
+        view.requestLayout();
+
+        mIsShowingView = true;
+        mPromoViewY = y;
+    }
+
+    /**
+     * Hides the Promo Android View. See {@link #showPromoView()}.
+     */
+    private void hidePromoView() {
+        View view = getView();
+        if (view == null
+                || !mIsVisible
+                || !mIsShowingView) {
+            return;
+        }
+
+        view.setVisibility(View.INVISIBLE);
+
+        mIsShowingView = false;
+    }
+
+    /**
+     * @return The current Y position of the Promo.
+     */
+    private float getYPx() {
+        return Math.round(
+                (mOverlayPanel.getOffsetY() + mOverlayPanel.getBarContainerHeight()) * mDpToPx);
+    }
+
+    /**
+     * Calculates the content height of the Promo View, and adjusts the height of the Promo while
+     * preserving the proportion of the height with the content height. This should be called
+     * whenever the the size of the Promo View changes.
+     */
+    private void calculatePromoHeight() {
+        layout();
+
+        final float previousContentHeight = mContentHeightPx;
+        mContentHeightPx = getMeasuredHeight();
+
+        if (mIsVisible) {
+            // Calculates the ratio between the current height and the previous content height,
+            // and uses it to calculate the new height, while preserving the ratio.
+            final float ratio = mHeightPx / previousContentHeight;
+            mHeightPx = Math.round(mContentHeightPx * ratio);
+        }
+    }
+}
\ No newline at end of file
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/ContextualSearchSceneLayer.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/ContextualSearchSceneLayer.java
index f2fee4a5..df3a581 100644
--- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/ContextualSearchSceneLayer.java
+++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/scene_layer/ContextualSearchSceneLayer.java
@@ -10,6 +10,7 @@
 import org.chromium.chrome.browser.compositor.bottombar.contextualsearch.ContextualSearchIconSpriteControl;
 import org.chromium.chrome.browser.compositor.bottombar.contextualsearch.ContextualSearchPanel;
 import org.chromium.chrome.browser.compositor.bottombar.contextualsearch.ContextualSearchPeekPromoControl;
+import org.chromium.chrome.browser.compositor.bottombar.contextualsearch.ContextualSearchPromoControl;
 import org.chromium.content.browser.ContentViewCore;
 import org.chromium.ui.resources.ResourceManager;
 
@@ -41,16 +42,17 @@
             ContextualSearchPanel panel,
             ContextualSearchBarControl searchBarControl,
             ContextualSearchPeekPromoControl peekPromoControl,
+            ContextualSearchPromoControl promoControl,
             ContextualSearchIconSpriteControl spriteControl) {
 
         int searchContextViewId = searchBarControl.getSearchContextViewId();
         int searchTermViewId = searchBarControl.getSearchTermViewId();
         int searchCaptionViewId = searchBarControl.getCaptionViewId();
 
-        // TODO(pedrosimonetti): Move to Promo logic to its own control class.
-        boolean searchPromoVisible = panel.getPromoVisible();
-        float searchPromoHeightPx = panel.getPromoHeightPx();
-        float searchPromoOpacity = panel.getPromoOpacity();
+        int searchPromoViewId = promoControl.getViewId();
+        boolean searchPromoVisible = promoControl.isVisible();
+        float searchPromoHeightPx = promoControl.getHeightPx();
+        float searchPromoOpacity = promoControl.getOpacity();
 
         int searchPeekPromoTextViewId = peekPromoControl.getViewId();
         boolean searchPeekPromoVisible = peekPromoControl.isVisible();
@@ -104,7 +106,7 @@
                 ContextualSearchPanel.CLOSE_ICON_DRAWABLE_ID,
                 R.drawable.progress_bar_background,
                 R.drawable.progress_bar_foreground,
-                R.id.contextual_search_opt_out_promo,
+                searchPromoViewId,
                 R.drawable.contextual_search_promo_ripple,
                 searchPeekPromoTextViewId,
                 mDpToPx,
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManager.java b/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManager.java
index a5e0f76..7b86b523 100644
--- a/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManager.java
+++ b/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManager.java
@@ -740,6 +740,14 @@
         mIsAccessibilityModeEnabled = enabled;
     }
 
+    /**
+     * Notifies that the preference state has changed.
+     * @param isEnabled Whether the feature is enabled.
+     */
+    public void onContextualSearchPrefChanged(boolean isEnabled) {
+        mSearchPanel.onContextualSearchPrefChanged(isEnabled);
+    }
+
     // ============================================================================================
     // Observers
     // ============================================================================================
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchTabHelper.java b/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchTabHelper.java
index 01d7be3..ca0f84c 100644
--- a/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchTabHelper.java
+++ b/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchTabHelper.java
@@ -64,7 +64,7 @@
         mBaseContentViewCore = tab.getContentViewCore();
         // Add Contextual Search here in case it couldn't get added in onContentChanged() due to
         // being too early in initialization of Chrome (ContextualSearchManager being null).
-        setContextualSearchHooks(mBaseContentViewCore);
+        updateContextualSearchHooks(mBaseContentViewCore);
 
         ContextualSearchManager manager = getContextualSearchManager();
         if (manager != null) {
@@ -84,7 +84,7 @@
                     new TemplateUrlServiceObserver() {
                         @Override
                         public void onTemplateURLServiceChanged() {
-                            onContextualSearchPrefChanged();
+                            updateContextualSearchHooks(mBaseContentViewCore);
                         }
                     };
             TemplateUrlService.getInstance().addObserver(mTemplateUrlObserver);
@@ -126,15 +126,15 @@
     private void updateHooksForNewContentViewCore(Tab tab) {
         removeContextualSearchHooks(mBaseContentViewCore);
         mBaseContentViewCore = tab.getContentViewCore();
-        setContextualSearchHooks(mBaseContentViewCore);
+        updateContextualSearchHooks(mBaseContentViewCore);
     }
 
     /**
-     * Sets up the Contextual Search hooks, adding or removing them depending on whether it is
+     * Updates the Contextual Search hooks, adding or removing them depending on whether it is
      * currently active.
      * @param cvc The content view core to attach the gesture state listener to.
      */
-    private void setContextualSearchHooks(ContentViewCore cvc) {
+    private void updateContextualSearchHooks(ContentViewCore cvc) {
         if (cvc == null) return;
 
         if (isContextualSearchActive(cvc)) {
@@ -200,7 +200,14 @@
 
     @CalledByNative
     private void onContextualSearchPrefChanged() {
-        setContextualSearchHooks(mBaseContentViewCore);
+        updateContextualSearchHooks(mBaseContentViewCore);
+
+        ContextualSearchManager manager = getContextualSearchManager();
+        if (manager != null) {
+            boolean isEnabled = !PrefServiceBridge.getInstance().isContextualSearchDisabled()
+                    && !PrefServiceBridge.getInstance().isContextualSearchUninitialized();
+            manager.onContextualSearchPrefChanged(isEnabled);
+        }
     }
 
     private native long nativeInit(Profile profile);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadNotificationService.java b/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadNotificationService.java
index 59b9895..ac5bff8 100644
--- a/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadNotificationService.java
+++ b/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadNotificationService.java
@@ -296,7 +296,7 @@
                 intent, DownloadNotificationService.EXTRA_DOWNLOAD_FILE_NAME);
         DownloadSharedPreferenceEntry entry = null;
         if (intent.getAction() == ACTION_DOWNLOAD_PAUSE) {
-            removeSharedPreferenceEntry(guid);
+            notifyDownloadPaused(guid, false);
             // If browser process already goes away, the download should have already paused. Do
             // nothing in that case.
             if (!DownloadManagerService.hasDownloadManagerService()) return;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/download/OWNERS b/chrome/android/java/src/org/chromium/chrome/browser/download/OWNERS
new file mode 100644
index 0000000..5abf5a1
--- /dev/null
+++ b/chrome/android/java/src/org/chromium/chrome/browser/download/OWNERS
@@ -0,0 +1 @@
+qinmin@chromium.org
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/mojo/ChromeServiceRegistrar.java b/chrome/android/java/src/org/chromium/chrome/browser/mojo/ChromeServiceRegistrar.java
new file mode 100644
index 0000000..003449c
--- /dev/null
+++ b/chrome/android/java/src/org/chromium/chrome/browser/mojo/ChromeServiceRegistrar.java
@@ -0,0 +1,24 @@
+// Copyright 2016 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.chrome.browser.mojo;
+
+import android.content.Context;
+
+import org.chromium.base.annotations.CalledByNative;
+import org.chromium.chrome.browser.payments.PaymentRequestFactory;
+import org.chromium.content.browser.ServiceRegistry;
+import org.chromium.mojom.payments.PaymentRequest;
+
+/**
+ * Registers mojo services exposed by Chrome in the given registry.
+ */
+class ChromeServiceRegistrar {
+    @CalledByNative
+    private static void registerRenderFrameMojoServices(
+            ServiceRegistry registry, Context applicationContext) {
+        assert applicationContext != null;
+        registry.addService(PaymentRequest.MANAGER, new PaymentRequestFactory(applicationContext));
+    }
+}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentRequestDialog.java b/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentRequestDialog.java
new file mode 100644
index 0000000..5002b9d
--- /dev/null
+++ b/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentRequestDialog.java
@@ -0,0 +1,58 @@
+// Copyright 2016 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.chrome.browser.payments;
+
+import android.content.Context;
+
+import org.chromium.mojo.system.MojoException;
+import org.chromium.mojom.payments.PaymentDetails;
+import org.chromium.mojom.payments.PaymentOptions;
+import org.chromium.mojom.payments.PaymentRequest;
+import org.chromium.mojom.payments.PaymentRequestClient;
+
+/**
+ * Android implementation of the PaymentRequest service defined in
+ * third_party/WebKit/public/platform/modules/payments/payment_request.mojom.
+ */
+public class PaymentRequestDialog implements PaymentRequest {
+    private final Context mApplicationContext;
+    private PaymentRequestClient mClient;
+
+    /**
+     * Builds the dialog.
+     *
+     * @param applicationContext The application context.
+     */
+    public PaymentRequestDialog(Context applicationContext) {
+        mApplicationContext = applicationContext;
+    }
+
+    @Override
+    public void setClient(PaymentRequestClient client) {
+        mClient = client;
+    }
+
+    @Override
+    public void show(String[] supportedMethods, PaymentDetails details, PaymentOptions options,
+            String stringifiedData) {
+        assert mClient != null;
+        mClient.onError();
+    }
+
+    @Override
+    public void abort() {}
+
+    @Override
+    public void complete(boolean success) {
+        assert mClient != null;
+        mClient.onComplete();
+    }
+
+    @Override
+    public void close() {}
+
+    @Override
+    public void onConnectionError(MojoException e) {}
+}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentRequestFactory.java b/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentRequestFactory.java
new file mode 100644
index 0000000..16167c7
--- /dev/null
+++ b/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentRequestFactory.java
@@ -0,0 +1,31 @@
+// Copyright 2016 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.chrome.browser.payments;
+
+import android.content.Context;
+
+import org.chromium.content.browser.ServiceRegistry.ImplementationFactory;
+import org.chromium.mojom.payments.PaymentRequest;
+
+/**
+ * Creates instances of PaymentRequest.
+ */
+public class PaymentRequestFactory implements ImplementationFactory<PaymentRequest> {
+    private final Context mApplicationContext;
+
+    /**
+     * Builds a factory for PaymentRequest.
+     *
+     * @param applicationContext The application context.
+     */
+    public PaymentRequestFactory(Context applicationContext) {
+        mApplicationContext = applicationContext;
+    }
+
+    @Override
+    public PaymentRequest createImpl() {
+        return new PaymentRequestDialog(mApplicationContext);
+    }
+}
diff --git a/chrome/android/java/strings/android_chrome_strings.grd b/chrome/android/java/strings/android_chrome_strings.grd
index 047b7c7..e6a15fe 100644
--- a/chrome/android/java/strings/android_chrome_strings.grd
+++ b/chrome/android/java/strings/android_chrome_strings.grd
@@ -368,7 +368,7 @@
       <message name="IDS_CONTEXTUAL_SEARCH_SHORT_DESCRIPTION" desc="A promo message shown to users who have Touch to Search enabled to explain the new behavior and provide an option to opt out">
         Touch to Search sends the selected word and the current page as context to Google Search. You can turn it off in <ph name="BEGIN_LINK">&lt;link&gt;</ph>Settings<ph name="END_LINK">&lt;/link&gt;</ph>.
       </message>
-      <message name="IDS_CONTEXTUAL_SEARCH_GOT_IT_BUTTON" desc="A button to confirm and dismiss opt out promo">
+      <message name="IDS_CONTEXTUAL_SEARCH_ALLOW_BUTTON" desc="A button to confirm and dismiss opt out promo">
         Allow
       </message>
       <message name="IDS_CONTEXTUAL_SEARCH_NO_THANKS_BUTTON" desc="A button to confirm and dismiss opt out promo">
diff --git a/chrome/android/java_sources.gni b/chrome/android/java_sources.gni
index b822423..6bd60a9 100644
--- a/chrome/android/java_sources.gni
+++ b/chrome/android/java_sources.gni
@@ -141,10 +141,10 @@
   "java/src/org/chromium/chrome/browser/compositor/bottombar/contextualsearch/ContextualSearchCaptionControl.java",
   "java/src/org/chromium/chrome/browser/compositor/bottombar/contextualsearch/ContextualSearchContextControl.java",
   "java/src/org/chromium/chrome/browser/compositor/bottombar/contextualsearch/ContextualSearchIconSpriteControl.java",
-  "java/src/org/chromium/chrome/browser/compositor/bottombar/contextualsearch/ContextualSearchOptOutPromo.java",
   "java/src/org/chromium/chrome/browser/compositor/bottombar/contextualsearch/ContextualSearchPanel.java",
   "java/src/org/chromium/chrome/browser/compositor/bottombar/contextualsearch/ContextualSearchPanelMetrics.java",
   "java/src/org/chromium/chrome/browser/compositor/bottombar/contextualsearch/ContextualSearchPeekPromoControl.java",
+  "java/src/org/chromium/chrome/browser/compositor/bottombar/contextualsearch/ContextualSearchPromoControl.java",
   "java/src/org/chromium/chrome/browser/compositor/bottombar/contextualsearch/ContextualSearchTermControl.java",
   "java/src/org/chromium/chrome/browser/compositor/bottombar/readermode/ReaderModeBarControl.java",
   "java/src/org/chromium/chrome/browser/compositor/bottombar/readermode/ReaderModePanel.java",
@@ -450,6 +450,7 @@
   "java/src/org/chromium/chrome/browser/metrics/UmaUtils.java",
   "java/src/org/chromium/chrome/browser/metrics/VariationsSession.java",
   "java/src/org/chromium/chrome/browser/metrics/WebappUma.java",
+  "java/src/org/chromium/chrome/browser/mojo/ChromeServiceRegistrar.java",
   "java/src/org/chromium/chrome/browser/multiwindow/MultiInstanceChromeTabbedActivity.java",
   "java/src/org/chromium/chrome/browser/multiwindow/MultiWindowUtils.java",
   "java/src/org/chromium/chrome/browser/net/qualityprovider/ExternalEstimateProviderAndroid.java",
@@ -566,6 +567,8 @@
   "java/src/org/chromium/chrome/browser/password_manager/AccountChooserDialog.java",
   "java/src/org/chromium/chrome/browser/password_manager/AutoSigninFirstRunDialog.java",
   "java/src/org/chromium/chrome/browser/password_manager/Credential.java",
+  "java/src/org/chromium/chrome/browser/payments/PaymentRequestDialog.java",
+  "java/src/org/chromium/chrome/browser/payments/PaymentRequestFactory.java",
   "java/src/org/chromium/chrome/browser/physicalweb/BitmapHttpRequest.java",
   "java/src/org/chromium/chrome/browser/physicalweb/ClearNotificationAlarmReceiver.java",
   "java/src/org/chromium/chrome/browser/physicalweb/HttpRequest.java",
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchEventFilterTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchEventFilterTest.java
index 6f19e00..f0243629 100644
--- a/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchEventFilterTest.java
+++ b/chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchEventFilterTest.java
@@ -162,12 +162,6 @@
             @Override
             public void removeLastHistoryEntry(String url, long timeInMs) {}
         }
-
-        @Override
-        protected float getPeekPromoHeight() {
-            // Android Views are not used in this test so we cannot get the actual height.
-            return 0.f;
-        }
     }
 
     // --------------------------------------------------------------------------------------------
diff --git a/chrome/app/generated_resources.grd b/chrome/app/generated_resources.grd
index c34bf157..47ef478b 100644
--- a/chrome/app/generated_resources.grd
+++ b/chrome/app/generated_resources.grd
@@ -7576,6 +7576,9 @@
       <message name="IDS_CLEAR_BROWSING_DATA_HISTORY_NOTICE_TITLE" desc="Title of a dialog that informs the user that the deletion of Chrome's browsing data has been completed.">
         Cleared Chrome data
       </message>
+      <message name="IDS_CLEAR_BROWSING_DATA_HISTORY_NOTICE_OK" desc="Button in a dialog that informs the user that the deletion of Chrome's browsing data has been completed.">
+        Ok, got it
+      </message>
       <message name="IDS_CLEAR_BROWSING_DATA_SYNCED_DELETION" desc="Information that data which is synced across user's devices will be deleted from all those devices.">
         This clears synced data from all devices.
       </message>
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc
index 19b8ed38..69b054e 100644
--- a/chrome/browser/about_flags.cc
+++ b/chrome/browser/about_flags.cc
@@ -254,28 +254,6 @@
     switches::kUseSimpleCacheBackend, "on"}
 };
 
-#if defined(USE_AURA)
-const FeatureEntry::Choice kTabCaptureUpscaleQualityChoices[] = {
-  { IDS_GENERIC_EXPERIMENT_CHOICE_DEFAULT, "", "" },
-  { IDS_FLAGS_TAB_CAPTURE_SCALE_QUALITY_FAST,
-    switches::kTabCaptureUpscaleQuality, "fast" },
-  { IDS_FLAGS_TAB_CAPTURE_SCALE_QUALITY_GOOD,
-    switches::kTabCaptureUpscaleQuality, "good" },
-  { IDS_FLAGS_TAB_CAPTURE_SCALE_QUALITY_BEST,
-    switches::kTabCaptureUpscaleQuality, "best" },
-};
-
-const FeatureEntry::Choice kTabCaptureDownscaleQualityChoices[] = {
-  { IDS_GENERIC_EXPERIMENT_CHOICE_DEFAULT, "", "" },
-  { IDS_FLAGS_TAB_CAPTURE_SCALE_QUALITY_FAST,
-    switches::kTabCaptureDownscaleQuality, "fast" },
-  { IDS_FLAGS_TAB_CAPTURE_SCALE_QUALITY_GOOD,
-    switches::kTabCaptureDownscaleQuality, "good" },
-  { IDS_FLAGS_TAB_CAPTURE_SCALE_QUALITY_BEST,
-    switches::kTabCaptureDownscaleQuality, "best" },
-};
-#endif
-
 #if defined(OS_ANDROID)
 const FeatureEntry::Choice kReaderModeHeuristicsChoices[] = {
     { IDS_GENERIC_EXPERIMENT_CHOICE_DEFAULT, "", ""},
@@ -1110,15 +1088,6 @@
      IDS_FLAGS_CLOUD_PRINT_XPS_DESCRIPTION, kOsWin,
      SINGLE_VALUE_TYPE(switches::kEnableCloudPrintXps)},
 #endif
-#if defined(USE_AURA)
-    {"tab-capture-upscale-quality", IDS_FLAGS_TAB_CAPTURE_UPSCALE_QUALITY_NAME,
-     IDS_FLAGS_TAB_CAPTURE_UPSCALE_QUALITY_DESCRIPTION, kOsAll,
-     MULTI_VALUE_TYPE(kTabCaptureUpscaleQualityChoices)},
-    {"tab-capture-downscale-quality",
-     IDS_FLAGS_TAB_CAPTURE_DOWNSCALE_QUALITY_NAME,
-     IDS_FLAGS_TAB_CAPTURE_DOWNSCALE_QUALITY_DESCRIPTION, kOsAll,
-     MULTI_VALUE_TYPE(kTabCaptureDownscaleQualityChoices)},
-#endif
 #if defined(TOOLKIT_VIEWS)
     {"disable-hide-inactive-stacked-tab-close-buttons",
      IDS_FLAGS_HIDE_INACTIVE_STACKED_TAB_CLOSE_BUTTONS_NAME,
diff --git a/chrome/browser/android/chrome_jni_registrar.cc b/chrome/browser/android/chrome_jni_registrar.cc
index 2e7679fa..1e89414 100644
--- a/chrome/browser/android/chrome_jni_registrar.cc
+++ b/chrome/browser/android/chrome_jni_registrar.cc
@@ -57,6 +57,7 @@
 #include "chrome/browser/android/metrics/uma_session_stats.h"
 #include "chrome/browser/android/metrics/uma_utils.h"
 #include "chrome/browser/android/metrics/variations_session.h"
+#include "chrome/browser/android/mojo/chrome_service_registrar_android.h"
 #include "chrome/browser/android/net/external_estimate_provider_android.h"
 #include "chrome/browser/android/ntp/most_visited_sites.h"
 #include "chrome/browser/android/ntp/new_tab_page_prefs.h"
@@ -245,6 +246,7 @@
     {"ChromeMediaRouterDialogController",
      media_router::MediaRouterDialogControllerAndroid::Register},
 #endif
+    {"ChromeServiceRegistrar", ChromeServiceRegistrarAndroid::Register},
     {"CompositorView", RegisterCompositorView},
     {"ConfirmInfoBar", RegisterConfirmInfoBar},
     {"ConnectionInfoPopupAndroid",
diff --git a/chrome/browser/android/mojo/chrome_service_registrar_android.cc b/chrome/browser/android/mojo/chrome_service_registrar_android.cc
new file mode 100644
index 0000000..c7749ad
--- /dev/null
+++ b/chrome/browser/android/mojo/chrome_service_registrar_android.cc
@@ -0,0 +1,24 @@
+// Copyright 2016 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 "chrome/browser/android/mojo/chrome_service_registrar_android.h"
+
+#include "base/android/context_utils.h"
+#include "base/android/jni_android.h"
+#include "content/public/browser/android/service_registry_android.h"
+#include "jni/ChromeServiceRegistrar_jni.h"
+
+// static
+bool ChromeServiceRegistrarAndroid::Register(JNIEnv* env) {
+  return RegisterNativesImpl(env);
+}
+
+// static
+void ChromeServiceRegistrarAndroid::RegisterRenderFrameMojoServices(
+    content::ServiceRegistry* registry) {
+  Java_ChromeServiceRegistrar_registerRenderFrameMojoServices(
+      base::android::AttachCurrentThread(),
+      content::ServiceRegistryAndroid::Create(registry)->GetObj().obj(),
+      base::android::GetApplicationContext());
+}
diff --git a/chrome/browser/android/mojo/chrome_service_registrar_android.h b/chrome/browser/android/mojo/chrome_service_registrar_android.h
new file mode 100644
index 0000000..e7b5feb6
--- /dev/null
+++ b/chrome/browser/android/mojo/chrome_service_registrar_android.h
@@ -0,0 +1,25 @@
+// Copyright 2016 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 CHROME_BROWSER_ANDROID_MOJO_CHROME_SERVICE_REGISTRAR_ANDROID_H_
+#define CHROME_BROWSER_ANDROID_MOJO_CHROME_SERVICE_REGISTRAR_ANDROID_H_
+
+#include <jni.h>
+
+namespace content {
+class ServiceRegistry;
+}
+
+class ChromeServiceRegistrarAndroid {
+ public:
+  static bool Register(JNIEnv* env);
+  static void RegisterRenderFrameMojoServices(
+      content::ServiceRegistry* registry);
+
+ private:
+  ChromeServiceRegistrarAndroid() {}
+  ~ChromeServiceRegistrarAndroid() {}
+};
+
+#endif  // CHROME_BROWSER_ANDROID_MOJO_CHROME_SERVICE_REGISTRAR_ANDROID_H_
diff --git a/chrome/browser/android/preferences/pref_service_bridge.cc b/chrome/browser/android/preferences/pref_service_bridge.cc
index f7bf301..4b829dd 100644
--- a/chrome/browser/android/preferences/pref_service_bridge.cc
+++ b/chrome/browser/android/preferences/pref_service_bridge.cc
@@ -163,11 +163,10 @@
                                         int setting) {
   HostContentSettingsMap* host_content_settings_map =
       HostContentSettingsMapFactory::GetForProfile(GetOriginalProfile());
-  host_content_settings_map->SetContentSetting(
+  host_content_settings_map->SetContentSettingCustomScope(
       ContentSettingsPattern::FromString(ConvertJavaStringToUTF8(env, pattern)),
       ContentSettingsPattern::Wildcard(),
-      static_cast<ContentSettingsType>(content_settings_type),
-      std::string(),
+      static_cast<ContentSettingsType>(content_settings_type), std::string(),
       static_cast<ContentSetting>(setting));
 }
 
diff --git a/chrome/browser/chrome_content_browser_client.cc b/chrome/browser/chrome_content_browser_client.cc
index 11dc2641..b43b8e3 100644
--- a/chrome/browser/chrome_content_browser_client.cc
+++ b/chrome/browser/chrome_content_browser_client.cc
@@ -216,6 +216,7 @@
 #endif
 
 #if BUILDFLAG(ANDROID_JAVA_UI)
+#include "chrome/browser/android/mojo/chrome_service_registrar_android.h"
 #include "chrome/browser/android/ntp/new_tab_page_url_handler.h"
 #include "chrome/browser/android/webapps/single_tab_mode_tab_helper.h"
 #include "components/service_tab_launcher/browser/android/service_tab_launcher.h"
@@ -2004,6 +2005,11 @@
   return AllowWebBluetoothResult::ALLOW;
 }
 
+std::string ChromeContentBrowserClient::GetWebBluetoothBlacklist() {
+  return variations::GetVariationParamValue("WebBluetoothBlacklist",
+                                            "blacklist_additions");
+}
+
 net::URLRequestContext*
 ChromeContentBrowserClient::OverrideRequestContextForURL(
     const GURL& url, content::ResourceContext* context) {
@@ -2786,6 +2792,10 @@
     registry->AddService(
         base::Bind(&CreateWebUsbChooserService, render_frame_host));
   }
+
+#if BUILDFLAG(ANDROID_JAVA_UI)
+  ChromeServiceRegistrarAndroid::RegisterRenderFrameMojoServices(registry);
+#endif
 }
 
 void ChromeContentBrowserClient::RegisterInProcessMojoApplications(
diff --git a/chrome/browser/chrome_content_browser_client.h b/chrome/browser/chrome_content_browser_client.h
index f0efaa6..f75706a 100644
--- a/chrome/browser/chrome_content_browser_client.h
+++ b/chrome/browser/chrome_content_browser_client.h
@@ -160,19 +160,17 @@
       const base::string16& name,
       content::ResourceContext* context,
       const std::vector<std::pair<int, int>>& render_frames) override;
-
 #if defined(ENABLE_WEBRTC)
   bool AllowWebRTCIdentityCache(const GURL& url,
                                 const GURL& first_party_url,
                                 content::ResourceContext* context) override;
 #endif  // defined(ENABLE_WEBRTC)
-
   bool AllowKeygen(const GURL& url, content::ResourceContext* context) override;
   AllowWebBluetoothResult AllowWebBluetooth(
       content::BrowserContext* browser_context,
       const url::Origin& requesting_origin,
       const url::Origin& embedding_origin) override;
-
+  std::string GetWebBluetoothBlacklist() override;
   net::URLRequestContext* OverrideRequestContextForURL(
       const GURL& url,
       content::ResourceContext* context) override;
diff --git a/chrome/browser/chromeos/login/chrome_restart_request.cc b/chrome/browser/chromeos/login/chrome_restart_request.cc
index 47da53b..4026d3fa 100644
--- a/chrome/browser/chromeos/login/chrome_restart_request.cc
+++ b/chrome/browser/chromeos/login/chrome_restart_request.cc
@@ -137,8 +137,6 @@
     ::switches::kRendererStartupDialog,
     ::switches::kRootLayerScrolls,
     ::switches::kEnableShareGroupAsyncTextureUpload,
-    ::switches::kTabCaptureUpscaleQuality,
-    ::switches::kTabCaptureDownscaleQuality,
 #if defined(USE_X11) || defined(USE_OZONE)
     ::switches::kTouchCalibration,
 #endif
diff --git a/chrome/browser/content_settings/host_content_settings_map_unittest.cc b/chrome/browser/content_settings/host_content_settings_map_unittest.cc
index 945eabc1..8347f04 100644
--- a/chrome/browser/content_settings/host_content_settings_map_unittest.cc
+++ b/chrome/browser/content_settings/host_content_settings_map_unittest.cc
@@ -1157,7 +1157,7 @@
             host_content_settings_map->GetContentSetting(
                 host, host, CONTENT_SETTINGS_TYPE_KEYGEN, std::string()));
 
-  host_content_settings_map->SetContentSetting(
+  host_content_settings_map->SetContentSettingCustomScope(
       pattern, pattern, CONTENT_SETTINGS_TYPE_KEYGEN, std::string(),
       CONTENT_SETTING_ALLOW);
   // Because of the old formatted setting entry which has two same patterns,
diff --git a/chrome/browser/devtools/device/usb/android_usb_browsertest.cc b/chrome/browser/devtools/device/usb/android_usb_browsertest.cc
index 4e05165..294cb66 100644
--- a/chrome/browser/devtools/device/usb/android_usb_browsertest.cc
+++ b/chrome/browser/devtools/device/usb/android_usb_browsertest.cc
@@ -396,8 +396,13 @@
 class MockUsbDevice : public UsbDevice {
  public:
   MockUsbDevice()
-      : UsbDevice(0,
-                  0,
+      : UsbDevice(0x0200,  // usb_version
+                  0,       // device_class
+                  0,       // device_subclass
+                  0,       // device_protocol
+                  0,       // vendor_id
+                  0,       // product_id
+                  0x0100,  // device_version
                   base::UTF8ToUTF16(kDeviceManufacturer),
                   base::UTF8ToUTF16(kDeviceModel),
                   base::UTF8ToUTF16(kDeviceSerial)),
diff --git a/chrome/browser/extensions/api/input_ime/input_ime_api.cc b/chrome/browser/extensions/api/input_ime/input_ime_api.cc
index f45589e9..7e3028d 100644
--- a/chrome/browser/extensions/api/input_ime/input_ime_api.cc
+++ b/chrome/browser/extensions/api/input_ime/input_ime_api.cc
@@ -5,7 +5,10 @@
 #include "chrome/browser/extensions/api/input_ime/input_ime_api.h"
 
 #include "base/lazy_instance.h"
+#include "chrome/browser/chrome_notification_types.h"
 #include "chrome/common/extensions/api/input_ime.h"
+#include "content/public/browser/notification_registrar.h"
+#include "content/public/browser/notification_service.h"
 #include "extensions/browser/extension_registry.h"
 
 namespace input_ime = extensions::api::input_ime;
@@ -256,6 +259,16 @@
   return router;
 }
 
+void InputImeEventRouterFactory::RemoveProfile(Profile* profile) {
+  if (!profile || router_map_.empty())
+    return;
+  auto it = router_map_.find(profile);
+  if (it != router_map_.end()) {
+    delete it->second;
+    router_map_.erase(it);
+  }
+}
+
 ExtensionFunction::ResponseAction InputImeKeyEventHandledFunction::Run() {
   scoped_ptr<KeyEventHandled::Params> params(
       KeyEventHandled::Params::Create(*args_));
@@ -368,10 +381,22 @@
 
   EventRouter* event_router = EventRouter::Get(browser_context_);
   event_router->RegisterObserver(this, input_ime::OnFocus::kEventName);
+  registrar_.Add(this, chrome::NOTIFICATION_PROFILE_DESTROYED,
+                 content::NotificationService::AllSources());
+}
+
+void InputImeAPI::Observe(int type,
+                          const content::NotificationSource& source,
+                          const content::NotificationDetails& details) {
+  if (type == chrome::NOTIFICATION_PROFILE_DESTROYED) {
+    extensions::InputImeEventRouterFactory::GetInstance()->RemoveProfile(
+        content::Source<Profile>(source).ptr());
+  }
 }
 
 InputImeAPI::~InputImeAPI() {
   EventRouter::Get(browser_context_)->UnregisterObserver(this);
+  registrar_.RemoveAll();
 }
 
 static base::LazyInstance<BrowserContextKeyedAPIFactory<InputImeAPI> >
diff --git a/chrome/browser/extensions/api/input_ime/input_ime_api.h b/chrome/browser/extensions/api/input_ime/input_ime_api.h
index 26a56fb..85496332 100644
--- a/chrome/browser/extensions/api/input_ime/input_ime_api.h
+++ b/chrome/browser/extensions/api/input_ime/input_ime_api.h
@@ -17,6 +17,7 @@
 #include "chrome/browser/profiles/profile.h"
 #include "chrome/browser/ui/input_method/input_method_engine_base.h"
 #include "components/keyed_service/core/keyed_service.h"
+#include "content/public/browser/notification_observer.h"
 #include "extensions/browser/browser_context_keyed_api_factory.h"
 #include "extensions/browser/event_router.h"
 #include "extensions/browser/extension_function.h"
@@ -33,6 +34,10 @@
 
 class Profile;
 
+namespace content {
+class NotificationRegistrar;
+}
+
 namespace ui {
 class IMEEngineHandlerInterface;
 
@@ -105,6 +110,7 @@
  public:
   static InputImeEventRouterFactory* GetInstance();
   InputImeEventRouter* GetRouter(Profile* profile);
+  void RemoveProfile(Profile* profile);
 
  private:
   friend struct base::DefaultSingletonTraits<InputImeEventRouterFactory>;
@@ -164,7 +170,8 @@
 
 class InputImeAPI : public BrowserContextKeyedAPI,
                     public ExtensionRegistryObserver,
-                    public EventRouter::Observer {
+                    public EventRouter::Observer,
+                    public content::NotificationObserver {
  public:
   explicit InputImeAPI(content::BrowserContext* context);
   ~InputImeAPI() override;
@@ -182,6 +189,11 @@
   // EventRouter::Observer implementation.
   void OnListenerAdded(const EventListenerInfo& details) override;
 
+  // content::NotificationObserver:
+  void Observe(int type,
+               const content::NotificationSource& source,
+               const content::NotificationDetails& details) override;
+
  private:
   friend class BrowserContextKeyedAPIFactory<InputImeAPI>;
   InputImeEventRouter* input_ime_event_router();
@@ -197,6 +209,8 @@
   // Listen to extension load, unloaded notifications.
   ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver>
       extension_registry_observer_;
+
+  content::NotificationRegistrar registrar_;
 };
 
 InputImeEventRouter* GetInputImeEventRouter(Profile* profile);
diff --git a/chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.cc b/chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.cc
index ac018a3c..b2dac0c 100644
--- a/chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.cc
+++ b/chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.cc
@@ -232,7 +232,7 @@
 
   // Disable using the warning bubble for testing.
   if (disable_bubble_for_testing_) {
-    GetInputImeEventRouter(profile)->SetActiveEngine(extension_id());
+    event_router->SetActiveEngine(extension_id());
     return RespondNow(NoArguments());
   }
 
@@ -271,7 +271,12 @@
 
   // Activates this extension if user presses the 'OK' button.
   Profile* profile = Profile::FromBrowserContext(browser_context());
-  GetInputImeEventRouter(profile)->SetActiveEngine(extension_id());
+  InputImeEventRouter* event_router = GetInputImeEventRouter(profile);
+  if (!event_router) {
+    Respond(Error(kErrorNoActiveEngine));
+    return;
+  }
+  event_router->SetActiveEngine(extension_id());
 
   if (status == ImeWarningBubblePermissionStatus::GRANTED_AND_NEVER_SHOW) {
     // Updates the extension preference if user checks the 'Never show this
diff --git a/chrome/browser/extensions/api/tab_capture/tab_capture_performancetest.cc b/chrome/browser/extensions/api/tab_capture/tab_capture_performancetest.cc
index 759aa11..93ae279 100644
--- a/chrome/browser/extensions/api/tab_capture/tab_capture_performancetest.cc
+++ b/chrome/browser/extensions/api/tab_capture/tab_capture_performancetest.cc
@@ -41,12 +41,6 @@
                                  // when on GPU, nor to 60hz when not on GPU.
   kTestThroughWebRTC   = 1 << 3, // Send captured frames through webrtc
   kSmallWindow         = 1 << 4, // 1 = 800x600, 0 = 2000x1000
-
-  kScaleQualityMask    = 3 << 5, // two bits select which scaling quality
-  kScaleQualityDefault = 0 << 5, // to use on aura.
-  kScaleQualityFast    = 1 << 5,
-  kScaleQualityGood    = 2 << 5,
-  kScaleQualityBest    = 3 << 5,
 };
 
 class TabCapturePerformanceTest
@@ -63,19 +57,6 @@
     return base::CommandLine::ForCurrentProcess()->HasSwitch("enable-gpu");
   }
 
-  std::string ScalingMethod() const {
-    switch (GetParam() & kScaleQualityMask) {
-      case kScaleQualityFast:
-        return "fast";
-      case kScaleQualityGood:
-        return "good";
-      case kScaleQualityBest:
-        return "best";
-      default:
-        return "";
-    }
-  }
-
   std::string GetSuffixForTestFlags() {
     std::string suffix;
     if (HasFlag(kForceGpuComposited))
@@ -86,8 +67,6 @@
       suffix += "_novsync";
     if (HasFlag(kTestThroughWebRTC))
       suffix += "_webrtc";
-    if (!ScalingMethod().empty())
-      suffix += "_scale" + ScalingMethod();
     if (HasFlag(kSmallWindow))
       suffix += "_small";
     return suffix;
@@ -99,13 +78,6 @@
   }
 
   void SetUpCommandLine(base::CommandLine* command_line) override {
-    if (!ScalingMethod().empty()) {
-      command_line->AppendSwitchASCII(switches::kTabCaptureUpscaleQuality,
-                                      ScalingMethod());
-      command_line->AppendSwitchASCII(switches::kTabCaptureDownscaleQuality,
-                                      ScalingMethod());
-    }
-
     // Some of the tests may launch http requests through JSON or AJAX
     // which causes a security error (cross domain request) when the page
     // is loaded from the local file system ( file:// ). The following switch
@@ -239,24 +211,3 @@
         kTestThroughWebRTC | kDisableVsync,
         kTestThroughWebRTC | kDisableVsync | kUseGpu | kForceGpuComposited));
 
-#if defined(USE_AURA)
-// TODO(hubbe):
-// These are temporary tests for the purpose of determining what the
-// appropriate scaling quality is. Once that has been determined,
-// these tests will be removed.
-
-const int kScalingTestBase =
-    kTestThroughWebRTC | kDisableVsync | kUseGpu | kForceGpuComposited;
-
-INSTANTIATE_TEST_CASE_P(
-    ScalingTests,
-    TabCapturePerformanceTest,
-    testing::Values(
-        kScalingTestBase | kScaleQualityFast,
-        kScalingTestBase | kScaleQualityGood,
-        kScalingTestBase | kScaleQualityBest,
-        kScalingTestBase | kScaleQualityFast | kSmallWindow,
-        kScalingTestBase | kScaleQualityGood | kSmallWindow,
-        kScalingTestBase | kScaleQualityBest | kSmallWindow));
-
-#endif  // USE_AURA
diff --git a/chrome/browser/notifications/message_center_settings_controller.cc b/chrome/browser/notifications/message_center_settings_controller.cc
index 6eac09b..f0e14e7 100644
--- a/chrome/browser/notifications/message_center_settings_controller.cc
+++ b/chrome/browser/notifications/message_center_settings_controller.cc
@@ -355,10 +355,11 @@
         // here because pattern might be from user manual input and not match
         // the default one used by ClearSetting().
         HostContentSettingsMapFactory::GetForProfile(profile)
-            ->SetContentSetting(pattern, ContentSettingsPattern::Wildcard(),
-                                CONTENT_SETTINGS_TYPE_NOTIFICATIONS,
-                                content_settings::ResourceIdentifier(),
-                                CONTENT_SETTING_DEFAULT);
+            ->SetContentSettingCustomScope(
+                pattern, ContentSettingsPattern::Wildcard(),
+                CONTENT_SETTINGS_TYPE_NOTIFICATIONS,
+                content_settings::ResourceIdentifier(),
+                CONTENT_SETTING_DEFAULT);
       }
     }
   } else {
diff --git a/chrome/browser/permissions/permission_manager_unittest.cc b/chrome/browser/permissions/permission_manager_unittest.cc
index 19cab7d..c780aaf 100644
--- a/chrome/browser/permissions/permission_manager_unittest.cc
+++ b/chrome/browser/permissions/permission_manager_unittest.cc
@@ -210,12 +210,8 @@
       base::Bind(&PermissionManagerTest::OnPermissionChange,
                  base::Unretained(this)));
 
-  GetHostContentSettingsMap()->SetContentSetting(
-      ContentSettingsPattern::Wildcard(),
-      ContentSettingsPattern::Wildcard(),
-      CONTENT_SETTINGS_TYPE_GEOLOCATION,
-      std::string(),
-      CONTENT_SETTING_ALLOW);
+  GetHostContentSettingsMap()->SetDefaultContentSetting(
+      CONTENT_SETTINGS_TYPE_GEOLOCATION, CONTENT_SETTING_ALLOW);
 
   EXPECT_TRUE(callback_called());
   EXPECT_EQ(PermissionStatus::GRANTED, callback_result());
diff --git a/chrome/browser/plugins/plugin_info_message_filter.cc b/chrome/browser/plugins/plugin_info_message_filter.cc
index 50ca2d1..59d7f8cc 100644
--- a/chrome/browser/plugins/plugin_info_message_filter.cc
+++ b/chrome/browser/plugins/plugin_info_message_filter.cc
@@ -330,6 +330,14 @@
     const WebPluginInfo& plugin,
     const PluginMetadata* plugin_metadata,
     ChromeViewHostMsg_GetPluginInfo_Status* status) const {
+  PluginMetadata::SecurityStatus plugin_status =
+      plugin_metadata->GetSecurityStatus(plugin);
+
+  if (plugin_status == PluginMetadata::SECURITY_STATUS_FULLY_TRUSTED) {
+    *status = ChromeViewHostMsg_GetPluginInfo_Status::kAllowed;
+    return;
+  }
+
   ContentSetting plugin_setting = CONTENT_SETTING_DEFAULT;
   bool uses_default_content_setting = true;
   bool is_managed = false;
@@ -348,8 +356,6 @@
   DCHECK(plugin_setting != CONTENT_SETTING_ASK);
 
 #if defined(ENABLE_PLUGIN_INSTALLATION)
-  PluginMetadata::SecurityStatus plugin_status =
-      plugin_metadata->GetSecurityStatus(plugin);
   // Check if the plugin is outdated.
   if (plugin_status == PluginMetadata::SECURITY_STATUS_OUT_OF_DATE &&
       !allow_outdated_plugins_.GetValue()) {
diff --git a/chrome/browser/plugins/plugin_info_message_filter_unittest.cc b/chrome/browser/plugins/plugin_info_message_filter_unittest.cc
index c66faa5d..a98a2ce0 100644
--- a/chrome/browser/plugins/plugin_info_message_filter_unittest.cc
+++ b/chrome/browser/plugins/plugin_info_message_filter_unittest.cc
@@ -227,11 +227,9 @@
                          CONTENT_SETTING_DETECT_IMPORTANT_CONTENT);
 
   // Allow plugin "foo" on all sites.
-  map->SetContentSetting(ContentSettingsPattern::Wildcard(),
-                         ContentSettingsPattern::Wildcard(),
-                         CONTENT_SETTINGS_TYPE_PLUGINS,
-                         "foo",
-                         CONTENT_SETTING_ALLOW);
+  map->SetContentSettingCustomScope(
+      ContentSettingsPattern::Wildcard(), ContentSettingsPattern::Wildcard(),
+      CONTENT_SETTINGS_TYPE_PLUGINS, "foo", CONTENT_SETTING_ALLOW);
 
   GURL unmatched_host("https://www.google.com");
   ASSERT_EQ(CONTENT_SETTING_BLOCK, map->GetContentSetting(
diff --git a/chrome/browser/plugins/plugin_metadata.cc b/chrome/browser/plugins/plugin_metadata.cc
index b99f3ee..0c42dde 100644
--- a/chrome/browser/plugins/plugin_metadata.cc
+++ b/chrome/browser/plugins/plugin_metadata.cc
@@ -89,6 +89,8 @@
     *status = SECURITY_STATUS_OUT_OF_DATE;
   else if (status_str == "requires_authorization")
     *status = SECURITY_STATUS_REQUIRES_AUTHORIZATION;
+  else if (status_str == "fully_trusted")
+    *status = SECURITY_STATUS_FULLY_TRUSTED;
   else
     return false;
 
diff --git a/chrome/browser/plugins/plugin_metadata.h b/chrome/browser/plugins/plugin_metadata.h
index 679e8c6..726853e 100644
--- a/chrome/browser/plugins/plugin_metadata.h
+++ b/chrome/browser/plugins/plugin_metadata.h
@@ -24,6 +24,7 @@
     SECURITY_STATUS_UP_TO_DATE,
     SECURITY_STATUS_OUT_OF_DATE,
     SECURITY_STATUS_REQUIRES_AUTHORIZATION,
+    SECURITY_STATUS_FULLY_TRUSTED,
   };
 
   // Used by about:plugins to disable Reader plugin when internal PDF viewer is
diff --git a/chrome/browser/plugins/plugin_power_saver_browsertest.cc b/chrome/browser/plugins/plugin_power_saver_browsertest.cc
index baa9e863..4ab99ea 100644
--- a/chrome/browser/plugins/plugin_power_saver_browsertest.cc
+++ b/chrome/browser/plugins/plugin_power_saver_browsertest.cc
@@ -411,7 +411,13 @@
                               "medium_16_9_cross_origin");
 }
 
-IN_PROC_BROWSER_TEST_F(PluginPowerSaverBrowserTest, SmallCrossOrigin) {
+// Flaky on WebKit Mac dbg bots: crbug.com/599484.
+#if defined(OS_MACOSX)
+#define MAYBE_SmallCrossOrigin DISABLED_SmallCrossOrigin
+#else
+#define MAYBE_SmallCrossOrigin SmallCrossOrigin
+#endif
+IN_PROC_BROWSER_TEST_F(PluginPowerSaverBrowserTest, MAYBE_SmallCrossOrigin) {
   LoadHTML(
       "<object id='plugin' data='http://otherorigin.com/fake.swf' "
       "    type='application/x-ppapi-tests' width='400' height='100'>"
@@ -452,7 +458,13 @@
       VerifySnapshot(FILE_PATH_LITERAL("smaller_than_play_icon_expected.png")));
 }
 
-IN_PROC_BROWSER_TEST_F(PluginPowerSaverBrowserTest, PosterTests) {
+// Flaky on WebKit Mac dbg bots: crbug.com/599484.
+#if defined(OS_MACOSX)
+#define MAYBE_PosterTests DISABLED_PosterTests
+#else
+#define MAYBE_PosterTests PosterTests
+#endif
+IN_PROC_BROWSER_TEST_F(PluginPowerSaverBrowserTest, MAYBE_PosterTests) {
   // This test simultaneously verifies the varied supported poster syntaxes,
   // as well as verifies that the poster is rendered correctly with various
   // mismatched aspect ratios and sizes, following the same rules as VIDEO.
diff --git a/chrome/browser/push_messaging/push_messaging_browsertest.cc b/chrome/browser/push_messaging/push_messaging_browsertest.cc
index c89a414..6a30357 100644
--- a/chrome/browser/push_messaging/push_messaging_browsertest.cc
+++ b/chrome/browser/push_messaging/push_messaging_browsertest.cc
@@ -1237,15 +1237,14 @@
 
   GURL origin = https_server()->GetURL("/").GetOrigin();
   HostContentSettingsMapFactory::GetForProfile(GetBrowser()->profile())
-      ->SetContentSetting(ContentSettingsPattern::Wildcard(),
-                          ContentSettingsPattern::Wildcard(),
-                          CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string(),
-                          CONTENT_SETTING_ALLOW);
+      ->SetDefaultContentSetting(CONTENT_SETTINGS_TYPE_NOTIFICATIONS,
+                                 CONTENT_SETTING_ALLOW);
   HostContentSettingsMapFactory::GetForProfile(GetBrowser()->profile())
-      ->SetContentSetting(ContentSettingsPattern::FromString("https://*"),
-                          ContentSettingsPattern::FromString("https://*"),
-                          CONTENT_SETTINGS_TYPE_PUSH_MESSAGING, std::string(),
-                          CONTENT_SETTING_ALLOW);
+      ->SetContentSettingCustomScope(
+          ContentSettingsPattern::FromString("https://*"),
+          ContentSettingsPattern::FromString("https://*"),
+          CONTENT_SETTINGS_TYPE_PUSH_MESSAGING, std::string(),
+          CONTENT_SETTING_ALLOW);
   HostContentSettingsMapFactory::GetForProfile(GetBrowser()->profile())
       ->SetContentSettingDefaultScope(origin, GURL(),
                                       CONTENT_SETTINGS_TYPE_NOTIFICATIONS,
diff --git a/chrome/browser/resources/chromeos/chromevox/manifest.json.jinja2 b/chrome/browser/resources/chromeos/chromevox/manifest.json.jinja2
index 8635c50..705fad83 100644
--- a/chrome/browser/resources/chromeos/chromevox/manifest.json.jinja2
+++ b/chrome/browser/resources/chromeos/chromevox/manifest.json.jinja2
@@ -33,6 +33,7 @@
           "chrome-extension://mndnfokpggljbaajbnioimlmbfngpief/cvox2/background/background.html",
           "chrome-extension://mndnfokpggljbaajbnioimlmbfngpief/chromevox/background/kbexplorer.html",
           "chrome-extension://mndnfokpggljbaajbnioimlmbfngpief/cvox2/background/panel.html",
+          "chrome-extension://nlkncpkkdoccmpiclbokaimcnedabhhm/gallery.html*",
           "chrome://md-settings*",
           "chrome://downloads*",
           "chrome://media-router*",
diff --git a/chrome/browser/resources/plugin_metadata/plugins_chromeos.json b/chrome/browser/resources/plugin_metadata/plugins_chromeos.json
index 86c4bae..a920c7e 100644
--- a/chrome/browser/resources/plugin_metadata/plugins_chromeos.json
+++ b/chrome/browser/resources/plugin_metadata/plugins_chromeos.json
@@ -1,5 +1,5 @@
 {
-  "x-version": 2,
+  "x-version": 3,
   "google-talk": {
     "mime_types": [
     ],
@@ -36,7 +36,7 @@
     "versions": [
       {
         "version": "0",
-        "status": "up_to_date",
+        "status": "fully_trusted",
         "comment": "Google Chrome PDF has no version information."
       }
     ],
@@ -49,8 +49,8 @@
     "versions": [
       {
         "version": "0",
-        "status": "up_to_date",
-        "comment": "Chrome PDF Viewer has no version information."
+        "status": "fully_trusted",
+        "comment": "Chromium PDF Viewer has no version information."
       }
     ],
     "name": "Chromium PDF Viewer",
diff --git a/chrome/browser/resources/plugin_metadata/plugins_linux.json b/chrome/browser/resources/plugin_metadata/plugins_linux.json
index 1bb4dac..35dbf10 100644
--- a/chrome/browser/resources/plugin_metadata/plugins_linux.json
+++ b/chrome/browser/resources/plugin_metadata/plugins_linux.json
@@ -1,5 +1,5 @@
 {
-  "x-version": 11,
+  "x-version": 12,
   "google-talk": {
     "mime_types": [
     ],
@@ -117,7 +117,7 @@
     "versions": [
       {
         "version": "0",
-        "status": "up_to_date",
+        "status": "fully_trusted",
         "comment": "Google Chrome PDF has no version information."
       }
     ],
@@ -130,8 +130,8 @@
     "versions": [
       {
         "version": "0",
-        "status": "up_to_date",
-        "comment": "Chrome PDF Viewer has no version information."
+        "status": "fully_trusted",
+        "comment": "Chromium PDF Viewer has no version information."
       }
     ],
     "name": "Chromium PDF Viewer",
diff --git a/chrome/browser/resources/plugin_metadata/plugins_mac.json b/chrome/browser/resources/plugin_metadata/plugins_mac.json
index ad658f7..853ad38c 100644
--- a/chrome/browser/resources/plugin_metadata/plugins_mac.json
+++ b/chrome/browser/resources/plugin_metadata/plugins_mac.json
@@ -1,5 +1,5 @@
 {
-  "x-version": 17,
+  "x-version": 18,
   "google-talk": {
     "mime_types": [
     ],
@@ -277,8 +277,8 @@
     "versions": [
       {
         "version": "0",
-        "status": "up_to_date",
-        "comment": "Chrome PDF Viewer has no version information."
+        "status": "fully_trusted",
+        "comment": "Google Chrome PDF Viewer has no version information."
       }
     ],
     "name": "Chrome PDF Viewer",
@@ -290,8 +290,8 @@
     "versions": [
       {
         "version": "0",
-        "status": "up_to_date",
-        "comment": "Chrome PDF Viewer has no version information."
+        "status": "fully_trusted",
+        "comment": "Chromium PDF Viewer has no version information."
       }
     ],
     "name": "Chromium PDF Viewer",
diff --git a/chrome/browser/resources/plugin_metadata/plugins_win.json b/chrome/browser/resources/plugin_metadata/plugins_win.json
index 68ee094..3c8870a 100644
--- a/chrome/browser/resources/plugin_metadata/plugins_win.json
+++ b/chrome/browser/resources/plugin_metadata/plugins_win.json
@@ -1,5 +1,5 @@
 {
-  "x-version": 26,
+  "x-version": 27,
   "google-talk": {
     "mime_types": [
     ],
@@ -339,8 +339,8 @@
     "versions": [
       {
         "version": "0",
-        "status": "up_to_date",
-        "comment": "Chrome PDF Viewer has no version information."
+        "status": "fully_trusted",
+        "comment": "Google Chrome PDF Viewer has no version information."
       }
     ],
     "name": "Chrome PDF Viewer",
@@ -352,8 +352,8 @@
     "versions": [
       {
         "version": "0",
-        "status": "up_to_date",
-        "comment": "Chrome PDF Viewer has no version information."
+        "status": "fully_trusted",
+        "comment": "Chromium PDF Viewer has no version information."
       }
     ],
     "name": "Chromium PDF Viewer",
diff --git a/chrome/browser/resources/plugins.html b/chrome/browser/resources/plugins.html
index 69ff555d..3dbd463b 100644
--- a/chrome/browser/resources/plugins.html
+++ b/chrome/browser/resources/plugins.html
@@ -191,7 +191,7 @@
             <input
                 class="always-allow" type="checkbox"
                 jsvalues=
-                    ".identifier:id; id:id + '-always-allowed'; .checked:always_allowed; disabled:!isPluginEnabled($this)">
+                    ".identifier:id; id:id + '-always-allowed'; .checked:always_allowed; disabled:isPluginTrusted($this) || !isPluginEnabled($this)">
             <label jsvalues="for:id + '-always-allowed'"
                 i18n-content="alwaysAllowed"></label>
           </div>
diff --git a/chrome/browser/resources/plugins.js b/chrome/browser/resources/plugins.js
index 4787c5c8..3301f2f 100644
--- a/chrome/browser/resources/plugins.js
+++ b/chrome/browser/resources/plugins.js
@@ -242,6 +242,15 @@
 }
 
 /**
+ * @param {Object} plugin An object containing the information about a plugin.
+ *     See returnPluginsData() for the format of this object.
+ * @return {boolean} Whether the plugin is fully trusted.
+ */
+function isPluginTrusted(plugin) {
+ return plugin.trusted == true;
+}
+
+/**
  * Helper to convert callback-based define() API to a promise-based API.
  * @param {!Array<string>} moduleNames
  * @return {!Promise}
diff --git a/chrome/browser/resources/settings/people_page/manage_profile.css b/chrome/browser/resources/settings/people_page/manage_profile.css
deleted file mode 100644
index fe8c87b..0000000
--- a/chrome/browser/resources/settings/people_page/manage_profile.css
+++ /dev/null
@@ -1,12 +0,0 @@
-/* Copyright (c) 2015 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. */
-
-paper-input {
-  width: 300px;
-}
-
-#availableIcons {
-  -webkit-margin-start: 16px;
-  margin-top: 16px;
-}
diff --git a/chrome/browser/resources/settings/people_page/manage_profile.html b/chrome/browser/resources/settings/people_page/manage_profile.html
index 5ef0061..0764ea8e 100644
--- a/chrome/browser/resources/settings/people_page/manage_profile.html
+++ b/chrome/browser/resources/settings/people_page/manage_profile.html
@@ -1,26 +1,62 @@
 <link rel="import" href="chrome://resources/html/polymer.html">
 <link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html">
+<link rel="import" href="chrome://resources/polymer/v1_0/iron-selector/iron-selector.html">
 <link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html">
 <link rel="import" href="chrome://resources/polymer/v1_0/paper-input/paper-input.html">
+<link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/shadow.html">
 <link rel="import" href="chrome://md-settings/people_page/manage_profile_browser_proxy.html">
 <link rel="import" href="chrome://md-settings/settings_shared_css.html">
 
 <dom-module id="settings-manage-profile">
-  <link rel="import" type="css" href="manage_profile.css">
   <template>
-    <style include="settings-shared"></style>
+    <style include="settings-shared">
+      #availableIcons {
+        -webkit-margin-start: 16px;
+        margin-top: 16px;
+        max-width: 600px;
+      }
+
+      #selector {
+        display: flex;
+        flex-wrap: wrap;
+      }
+
+      /* Special style for Manage Profile icon grid buttons only. */
+      paper-button {
+        align-items: center;
+        background-color: var(--paper-grey-300);
+        border: 1px solid var(--paper-grey-300);
+        border-radius: 4px;
+        display: flex;
+        height: 48px;
+        justify-content: center;
+        margin: 8px;
+        padding: 0;
+        width: 48px;
+      }
+
+      paper-button:hover {
+        @apply(--shadow-elevation-2dp);
+      }
+
+      paper-button.iron-selected {
+        border: 1px solid var(--google-blue-500);
+      }
+    </style>
     <div class="settings-box first">
       <paper-input value="{{profileName}}" pattern=".*\S.*" auto-validate
           required on-change="onProfileNameChanged_">
       </paper-input>
-      <div id="availableIcons">
+    </div>
+    <div id="availableIcons">
+      <iron-selector id="selector" on-iron-activate="onIconActivate_"
+          selected="[[profileIconUrl]]" attr-for-selected="data-icon-url">
         <template is="dom-repeat" items="[[availableIconUrls]]">
-          <paper-button toggles active="{{isActiveIcon_(item, profileIconUrl)}}"
-              on-tap="onIconTap_" data-icon-url$="[[item]]">
+          <paper-button data-icon-url$="[[item]]">
             <img src="[[item]]">
           </paper-button>
         </template>
-      </div>
+      </iron-selector>
     </div>
   </template>
   <script src="manage_profile.js"></script>
diff --git a/chrome/browser/resources/settings/people_page/manage_profile.js b/chrome/browser/resources/settings/people_page/manage_profile.js
index 96628485..243548d 100644
--- a/chrome/browser/resources/settings/people_page/manage_profile.js
+++ b/chrome/browser/resources/settings/people_page/manage_profile.js
@@ -66,37 +66,14 @@
   },
 
   /**
-   * Handler for when the user clicks a new profile icon.
-   * @private
+   * Handler for when the an image is activated.
    * @param {!Event} event
-   */
-  onIconTap_: function(event) {
-    var element = Polymer.dom(event).rootTarget;
-
-    var iconUrl;
-    if (element.nodeName == 'IMG')
-      iconUrl = element.src;
-    else if (element.dataset && element.dataset.iconUrl)
-      iconUrl = element.dataset.iconUrl;
-
-    if (!iconUrl)
-      return;
-
-    this.browserProxy_.setProfileIconAndName(iconUrl, this.profileName);
-
-    // Button toggle state is controlled by the selected icon URL. Prevent
-    // tap events from changing the toggle state.
-    event.preventDefault();
-  },
-
-  /**
-   * Computed binding determining which profile icon button is toggled on.
    * @private
-   * @param {string} iconUrl
-   * @param {string} profileIconUrl
-   * @return {boolean}
    */
-  isActiveIcon_: function(iconUrl, profileIconUrl) {
-    return iconUrl == profileIconUrl;
+  onIconActivate_: function(event) {
+    /** @type {{iconUrl: string}} */
+    var buttonData = event.detail.item.dataset;
+    this.browserProxy_.setProfileIconAndName(buttonData.iconUrl,
+                                             this.profileName);
   },
 });
diff --git a/chrome/browser/resources/settings/settings_resources.grd b/chrome/browser/resources/settings/settings_resources.grd
index efb35a0..4efe8913 100644
--- a/chrome/browser/resources/settings/settings_resources.grd
+++ b/chrome/browser/resources/settings/settings_resources.grd
@@ -443,9 +443,6 @@
                  flattenhtml="true"
                  allowexternalscript="true" />
       <if expr="not chromeos">
-        <structure name="IDR_SETTINGS_PEOPLE_PAGE_MANAGE_PROFILE_CSS"
-                   file="people_page/manage_profile.css"
-                   type="chrome_html" />
         <structure name="IDR_SETTINGS_PEOPLE_PAGE_MANAGE_PROFILE_HTML"
                    file="people_page/manage_profile.html"
                    type="chrome_html"
diff --git a/chrome/browser/ui/ash/chrome_shell_delegate.cc b/chrome/browser/ui/ash/chrome_shell_delegate.cc
index 08b3c39..22398ab 100644
--- a/chrome/browser/ui/ash/chrome_shell_delegate.cc
+++ b/chrome/browser/ui/ash/chrome_shell_delegate.cc
@@ -162,7 +162,7 @@
   if (chrome::IsRunningInAppMode())
     return nullptr;
 
-  return new LauncherContextMenu(shelf_delegate_, item, shelf);
+  return LauncherContextMenu::Create(shelf_delegate_, item, shelf);
 }
 
 ash::GPUSupport* ChromeShellDelegate::CreateGPUSupport() {
diff --git a/chrome/browser/ui/ash/launcher/desktop_shell_launcher_context_menu.cc b/chrome/browser/ui/ash/launcher/desktop_shell_launcher_context_menu.cc
new file mode 100644
index 0000000..acd9e86
--- /dev/null
+++ b/chrome/browser/ui/ash/launcher/desktop_shell_launcher_context_menu.cc
@@ -0,0 +1,19 @@
+// Copyright 2016 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 "chrome/browser/ui/ash/launcher/desktop_shell_launcher_context_menu.h"
+
+DesktopShellLauncherContextMenu::DesktopShellLauncherContextMenu(
+    ChromeLauncherController* controller,
+    const ash::ShelfItem* item,
+    ash::Shelf* shelf)
+    : LauncherContextMenu(controller, item, shelf) {
+  Init();
+}
+
+DesktopShellLauncherContextMenu::~DesktopShellLauncherContextMenu() {}
+
+void DesktopShellLauncherContextMenu::Init() {
+  AddShelfOptionsMenu();
+}
diff --git a/chrome/browser/ui/ash/launcher/desktop_shell_launcher_context_menu.h b/chrome/browser/ui/ash/launcher/desktop_shell_launcher_context_menu.h
new file mode 100644
index 0000000..f6b6e85
--- /dev/null
+++ b/chrome/browser/ui/ash/launcher/desktop_shell_launcher_context_menu.h
@@ -0,0 +1,32 @@
+// Copyright 2016 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 CHROME_BROWSER_UI_ASH_LAUNCHER_DESKTOP_SHELL_LAUNCHER_CONTEXT_MENU_H_
+#define CHROME_BROWSER_UI_ASH_LAUNCHER_DESKTOP_SHELL_LAUNCHER_CONTEXT_MENU_H_
+
+#include "base/macros.h"
+#include "chrome/browser/ui/ash/launcher/launcher_context_menu.h"
+
+class ChromeLauncherController;
+
+namespace ash {
+class Shelf;
+struct ShelfItem;
+}
+
+// Class for context menu which is shown when right click on desktop shell.
+class DesktopShellLauncherContextMenu : public LauncherContextMenu {
+ public:
+  DesktopShellLauncherContextMenu(ChromeLauncherController* controller,
+                                  const ash::ShelfItem* item,
+                                  ash::Shelf* shelf);
+  ~DesktopShellLauncherContextMenu() override;
+
+ private:
+  void Init();
+
+  DISALLOW_COPY_AND_ASSIGN(DesktopShellLauncherContextMenu);
+};
+
+#endif  // CHROME_BROWSER_UI_ASH_LAUNCHER_DESKTOP_SHELL_LAUNCHER_CONTEXT_MENU_H_
diff --git a/chrome/browser/ui/ash/launcher/extension_launcher_context_menu.cc b/chrome/browser/ui/ash/launcher/extension_launcher_context_menu.cc
new file mode 100644
index 0000000..cea24f8
--- /dev/null
+++ b/chrome/browser/ui/ash/launcher/extension_launcher_context_menu.cc
@@ -0,0 +1,220 @@
+// Copyright 2016 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 "chrome/browser/ui/ash/launcher/extension_launcher_context_menu.h"
+
+#include "ash/shelf/shelf.h"
+#include "ash/shelf/shelf_item_delegate.h"
+#include "base/bind.h"
+#include "chrome/browser/extensions/context_menu_matcher.h"
+#include "chrome/browser/extensions/extension_util.h"
+#include "chrome/browser/prefs/incognito_mode_prefs.h"
+#include "chrome/browser/profiles/profile.h"
+#include "chrome/browser/ui/ash/launcher/chrome_launcher_controller.h"
+#include "chrome/common/extensions/extension_constants.h"
+#include "chrome/grit/generated_resources.h"
+#include "content/public/common/context_menu_params.h"
+#include "grit/ash_strings.h"
+#include "ui/base/l10n/l10n_util.h"
+
+namespace {
+
+bool MenuItemHasLauncherContext(const extensions::MenuItem* item) {
+  return item->contexts().Contains(extensions::MenuItem::LAUNCHER);
+}
+
+}  // namespace
+
+ExtensionLauncherContextMenu::ExtensionLauncherContextMenu(
+    ChromeLauncherController* controller,
+    const ash::ShelfItem* item,
+    ash::Shelf* shelf)
+    : LauncherContextMenu(controller, item, shelf) {
+  Init();
+}
+
+ExtensionLauncherContextMenu::~ExtensionLauncherContextMenu() {}
+
+void ExtensionLauncherContextMenu::Init() {
+  extension_items_.reset(new extensions::ContextMenuMatcher(
+      controller()->profile(), this, this,
+      base::Bind(MenuItemHasLauncherContext)));
+  if (item().type == ash::TYPE_APP_SHORTCUT ||
+      item().type == ash::TYPE_WINDOWED_APP) {
+    // V1 apps can be started from the menu - but V2 apps should not.
+    if (!controller()->IsPlatformApp(item().id)) {
+      AddItem(MENU_OPEN_NEW, base::string16());
+      AddSeparator(ui::NORMAL_SEPARATOR);
+    }
+    AddPinMenu();
+    if (controller()->IsOpen(item().id))
+      AddItemWithStringId(MENU_CLOSE, IDS_LAUNCHER_CONTEXT_MENU_CLOSE);
+
+    if (!controller()->IsPlatformApp(item().id) &&
+        item().type != ash::TYPE_WINDOWED_APP) {
+      AddSeparator(ui::NORMAL_SEPARATOR);
+      if (extensions::util::IsNewBookmarkAppsEnabled()) {
+        // With bookmark apps enabled, hosted apps launch in a window by
+        // default. This menu item is re-interpreted as a single, toggle-able
+        // option to launch the hosted app as a tab.
+        AddCheckItemWithStringId(LAUNCH_TYPE_WINDOW,
+                                 IDS_APP_CONTEXT_MENU_OPEN_WINDOW);
+      } else {
+        AddCheckItemWithStringId(LAUNCH_TYPE_REGULAR_TAB,
+                                 IDS_APP_CONTEXT_MENU_OPEN_REGULAR);
+        AddCheckItemWithStringId(LAUNCH_TYPE_PINNED_TAB,
+                                 IDS_APP_CONTEXT_MENU_OPEN_PINNED);
+        AddCheckItemWithStringId(LAUNCH_TYPE_WINDOW,
+                                 IDS_APP_CONTEXT_MENU_OPEN_WINDOW);
+        // Even though the launch type is Full Screen it is more accurately
+        // described as Maximized in Ash.
+        AddCheckItemWithStringId(LAUNCH_TYPE_FULLSCREEN,
+                                 IDS_APP_CONTEXT_MENU_OPEN_MAXIMIZED);
+      }
+    }
+  } else if (item().type == ash::TYPE_BROWSER_SHORTCUT) {
+    AddItemWithStringId(MENU_NEW_WINDOW, IDS_APP_LIST_NEW_WINDOW);
+    if (!controller()->IsLoggedInAsGuest()) {
+      AddItemWithStringId(MENU_NEW_INCOGNITO_WINDOW,
+                          IDS_APP_LIST_NEW_INCOGNITO_WINDOW);
+    }
+  } else if (item().type == ash::TYPE_DIALOG) {
+    AddItemWithStringId(MENU_CLOSE, IDS_LAUNCHER_CONTEXT_MENU_CLOSE);
+  } else {
+    if (item().type == ash::TYPE_PLATFORM_APP)
+      AddItemWithStringId(MENU_PIN, IDS_LAUNCHER_CONTEXT_MENU_PIN);
+    bool show_close_button = controller()->IsOpen(item().id);
+#if defined(OS_CHROMEOS)
+    if (extension_misc::IsImeMenuExtensionId(
+            controller()->GetAppIDForShelfID(item().id)))
+      show_close_button = false;
+#endif
+    if (show_close_button)
+      AddItemWithStringId(MENU_CLOSE, IDS_LAUNCHER_CONTEXT_MENU_CLOSE);
+  }
+  AddSeparator(ui::NORMAL_SEPARATOR);
+  if (item().type == ash::TYPE_APP_SHORTCUT ||
+      item().type == ash::TYPE_WINDOWED_APP ||
+      item().type == ash::TYPE_PLATFORM_APP) {
+    const extensions::MenuItem::ExtensionKey app_key(
+        controller()->GetAppIDForShelfID(item().id));
+    if (!app_key.empty()) {
+      int index = 0;
+      extension_items_->AppendExtensionItems(app_key, base::string16(), &index,
+                                             false);  // is_action_menu
+      AddSeparator(ui::NORMAL_SEPARATOR);
+    }
+  }
+  AddShelfOptionsMenu();
+}
+
+bool ExtensionLauncherContextMenu::IsItemForCommandIdDynamic(
+    int command_id) const {
+  return command_id == MENU_OPEN_NEW;
+}
+
+base::string16 ExtensionLauncherContextMenu::GetLabelForCommandId(
+    int command_id) const {
+  if (command_id == MENU_OPEN_NEW) {
+    if (item().type == ash::TYPE_PLATFORM_APP)
+      return l10n_util::GetStringUTF16(IDS_APP_LIST_CONTEXT_MENU_NEW_WINDOW);
+    switch (controller()->GetLaunchType(item().id)) {
+      case extensions::LAUNCH_TYPE_PINNED:
+      case extensions::LAUNCH_TYPE_REGULAR:
+        return l10n_util::GetStringUTF16(IDS_APP_LIST_CONTEXT_MENU_NEW_TAB);
+      case extensions::LAUNCH_TYPE_FULLSCREEN:
+      case extensions::LAUNCH_TYPE_WINDOW:
+        return l10n_util::GetStringUTF16(IDS_APP_LIST_CONTEXT_MENU_NEW_WINDOW);
+      default:
+        NOTREACHED();
+        return base::string16();
+    }
+  }
+  NOTREACHED();
+  return base::string16();
+}
+
+bool ExtensionLauncherContextMenu::IsCommandIdChecked(int command_id) const {
+  switch (command_id) {
+    case LAUNCH_TYPE_PINNED_TAB:
+      return controller()->GetLaunchType(item().id) ==
+             extensions::LAUNCH_TYPE_PINNED;
+    case LAUNCH_TYPE_REGULAR_TAB:
+      return controller()->GetLaunchType(item().id) ==
+             extensions::LAUNCH_TYPE_REGULAR;
+    case LAUNCH_TYPE_WINDOW:
+      return controller()->GetLaunchType(item().id) ==
+             extensions::LAUNCH_TYPE_WINDOW;
+    case LAUNCH_TYPE_FULLSCREEN:
+      return controller()->GetLaunchType(item().id) ==
+             extensions::LAUNCH_TYPE_FULLSCREEN;
+    default:
+      if (command_id < MENU_ITEM_COUNT)
+        return LauncherContextMenu::IsCommandIdChecked(command_id);
+      return (extension_items_ &&
+              extension_items_->IsCommandIdChecked(command_id));
+  }
+}
+
+bool ExtensionLauncherContextMenu::IsCommandIdEnabled(int command_id) const {
+  switch (command_id) {
+    case MENU_NEW_WINDOW:
+      // "Normal" windows are not allowed when incognito is enforced.
+      return IncognitoModePrefs::GetAvailability(
+                 controller()->profile()->GetPrefs()) !=
+             IncognitoModePrefs::FORCED;
+    case MENU_NEW_INCOGNITO_WINDOW:
+      // Incognito windows are not allowed when incognito is disabled.
+      return IncognitoModePrefs::GetAvailability(
+                 controller()->profile()->GetPrefs()) !=
+             IncognitoModePrefs::DISABLED;
+    default:
+      if (command_id < MENU_ITEM_COUNT)
+        return LauncherContextMenu::IsCommandIdEnabled(command_id);
+      return (extension_items_ &&
+              extension_items_->IsCommandIdEnabled(command_id));
+  }
+}
+
+void ExtensionLauncherContextMenu::ExecuteCommand(int command_id,
+                                                  int event_flags) {
+  if (ExecuteCommonCommand(command_id, event_flags))
+    return;
+  switch (static_cast<MenuItem>(command_id)) {
+    case LAUNCH_TYPE_PINNED_TAB:
+      controller()->SetLaunchType(item().id, extensions::LAUNCH_TYPE_PINNED);
+      break;
+    case LAUNCH_TYPE_REGULAR_TAB:
+      controller()->SetLaunchType(item().id, extensions::LAUNCH_TYPE_REGULAR);
+      break;
+    case LAUNCH_TYPE_WINDOW: {
+      extensions::LaunchType launch_type = extensions::LAUNCH_TYPE_WINDOW;
+      // With bookmark apps enabled, hosted apps can only toggle between
+      // LAUNCH_WINDOW and LAUNCH_REGULAR.
+      if (extensions::util::IsNewBookmarkAppsEnabled()) {
+        launch_type = controller()->GetLaunchType(item().id) ==
+                              extensions::LAUNCH_TYPE_WINDOW
+                          ? extensions::LAUNCH_TYPE_REGULAR
+                          : extensions::LAUNCH_TYPE_WINDOW;
+      }
+      controller()->SetLaunchType(item().id, launch_type);
+      break;
+    }
+    case LAUNCH_TYPE_FULLSCREEN:
+      controller()->SetLaunchType(item().id,
+                                  extensions::LAUNCH_TYPE_FULLSCREEN);
+      break;
+    case MENU_NEW_WINDOW:
+      controller()->CreateNewWindow();
+      break;
+    case MENU_NEW_INCOGNITO_WINDOW:
+      controller()->CreateNewIncognitoWindow();
+      break;
+    default:
+      if (extension_items_) {
+        extension_items_->ExecuteCommand(command_id, nullptr, nullptr,
+                                         content::ContextMenuParams());
+      }
+  }
+}
diff --git a/chrome/browser/ui/ash/launcher/extension_launcher_context_menu.h b/chrome/browser/ui/ash/launcher/extension_launcher_context_menu.h
new file mode 100644
index 0000000..4c7eec66
--- /dev/null
+++ b/chrome/browser/ui/ash/launcher/extension_launcher_context_menu.h
@@ -0,0 +1,47 @@
+// Copyright 2016 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 CHROME_BROWSER_UI_ASH_LAUNCHER_EXTENSION_LAUNCHER_CONTEXT_MENU_H_
+#define CHROME_BROWSER_UI_ASH_LAUNCHER_EXTENSION_LAUNCHER_CONTEXT_MENU_H_
+
+#include "base/macros.h"
+#include "base/memory/scoped_ptr.h"
+#include "chrome/browser/ui/ash/launcher/launcher_context_menu.h"
+
+class ChromeLauncherController;
+
+namespace ash {
+class Shelf;
+struct ShelfItem;
+}
+
+namespace extensions {
+class ContextMenuMatcher;
+}
+
+// Class for context menu which is shown for a regular extension item in the
+// shelf.
+class ExtensionLauncherContextMenu : public LauncherContextMenu {
+ public:
+  ExtensionLauncherContextMenu(ChromeLauncherController* controller,
+                               const ash::ShelfItem* item,
+                               ash::Shelf* shelf);
+  ~ExtensionLauncherContextMenu() override;
+
+  // ui::SimpleMenuModel::Delegate overrides:
+  bool IsItemForCommandIdDynamic(int command_id) const override;
+  base::string16 GetLabelForCommandId(int command_id) const override;
+  bool IsCommandIdChecked(int command_id) const override;
+  bool IsCommandIdEnabled(int command_id) const override;
+  void ExecuteCommand(int command_id, int event_flags) override;
+
+ private:
+  void Init();
+
+  scoped_ptr<extensions::ContextMenuMatcher> extension_items_;
+
+  DISALLOW_COPY_AND_ASSIGN(ExtensionLauncherContextMenu);
+};
+
+#endif  // CHROME_BROWSER_UI_ASH_LAUNCHER_EXTENSION_LAUNCHER_CONTEXT_MENU_H_
diff --git a/chrome/browser/ui/ash/launcher/launcher_context_menu.cc b/chrome/browser/ui/ash/launcher/launcher_context_menu.cc
index 1539ae9e..907c1638 100644
--- a/chrome/browser/ui/ash/launcher/launcher_context_menu.cc
+++ b/chrome/browser/ui/ash/launcher/launcher_context_menu.cc
@@ -10,19 +10,13 @@
 #include "ash/metrics/user_metrics_recorder.h"
 #include "ash/session/session_state_delegate.h"
 #include "ash/shelf/shelf.h"
-#include "ash/shelf/shelf_item_delegate.h"
-#include "ash/shelf/shelf_widget.h"
 #include "ash/shell.h"
-#include "base/bind.h"
 #include "build/build_config.h"
-#include "chrome/browser/extensions/context_menu_matcher.h"
-#include "chrome/browser/extensions/extension_util.h"
 #include "chrome/browser/fullscreen.h"
-#include "chrome/browser/prefs/incognito_mode_prefs.h"
 #include "chrome/browser/profiles/profile.h"
-#include "chrome/browser/ui/ash/chrome_shell_delegate.h"
 #include "chrome/browser/ui/ash/launcher/chrome_launcher_controller.h"
-#include "chrome/common/extensions/extension_constants.h"
+#include "chrome/browser/ui/ash/launcher/desktop_shell_launcher_context_menu.h"
+#include "chrome/browser/ui/ash/launcher/extension_launcher_context_menu.h"
 #include "chrome/common/pref_names.h"
 #include "chrome/grit/generated_resources.h"
 #include "components/prefs/pref_service.h"
@@ -32,10 +26,6 @@
 
 namespace {
 
-bool MenuItemHasLauncherContext(const extensions::MenuItem* item) {
-  return item->contexts().Contains(extensions::MenuItem::LAUNCHER);
-}
-
 // Returns true if the user can modify the |shelf|'s auto-hide behavior.
 bool CanUserModifyShelfAutoHideBehavior(const Profile* profile) {
   const std::string& pref = prefs::kShelfAutoHideBehaviorLocal;
@@ -44,6 +34,21 @@
 
 }  // namespace
 
+// static
+LauncherContextMenu* LauncherContextMenu::Create(
+    ChromeLauncherController* controller,
+    const ash::ShelfItem* item,
+    ash::Shelf* shelf) {
+  DCHECK(controller);
+  DCHECK(shelf);
+  // Create DesktopShellLauncherContextMenu if no item is selected.
+  if (!item || item->id == 0)
+    return new DesktopShellLauncherContextMenu(controller, item, shelf);
+
+  // Create ExtensionLauncherContextMenu for the item.
+  return new ExtensionLauncherContextMenu(controller, item, shelf);
+}
+
 LauncherContextMenu::LauncherContextMenu(ChromeLauncherController* controller,
                                          const ash::ShelfItem* item,
                                          ash::Shelf* shelf)
@@ -52,180 +57,28 @@
       item_(item ? *item : ash::ShelfItem()),
       shelf_alignment_menu_(shelf),
       shelf_(shelf) {
-  DCHECK(shelf_);
-  Init();
-}
-
-void LauncherContextMenu::Init() {
   set_delegate(this);
-
-  if (item_.id != 0) {
-    extension_items_.reset(new extensions::ContextMenuMatcher(
-        controller_->profile(), this, this,
-        base::Bind(MenuItemHasLauncherContext)));
-    if (item_.type == ash::TYPE_APP_SHORTCUT ||
-        item_.type == ash::TYPE_WINDOWED_APP) {
-      // V1 apps can be started from the menu - but V2 apps should not.
-      if (!controller_->IsPlatformApp(item_.id)) {
-        AddItem(MENU_OPEN_NEW, base::string16());
-        AddSeparator(ui::NORMAL_SEPARATOR);
-      }
-      const std::string app_id = controller_->GetAppIDForShelfID(item_.id);
-      int menu_pin_string_id;
-      if (!controller_->CanPin(app_id))
-        menu_pin_string_id = IDS_LAUNCHER_CONTEXT_MENU_PIN_ENFORCED_BY_POLICY;
-      else if (controller_->IsPinned(item_.id))
-        menu_pin_string_id = IDS_LAUNCHER_CONTEXT_MENU_UNPIN;
-      else
-        menu_pin_string_id = IDS_LAUNCHER_CONTEXT_MENU_PIN;
-      AddItem(MENU_PIN, l10n_util::GetStringUTF16(menu_pin_string_id));
-      if (controller_->IsOpen(item_.id)) {
-        AddItem(MENU_CLOSE,
-                l10n_util::GetStringUTF16(IDS_LAUNCHER_CONTEXT_MENU_CLOSE));
-      }
-      if (!controller_->IsPlatformApp(item_.id) &&
-          item_.type != ash::TYPE_WINDOWED_APP) {
-        AddSeparator(ui::NORMAL_SEPARATOR);
-        if (extensions::util::IsNewBookmarkAppsEnabled()) {
-          // With bookmark apps enabled, hosted apps launch in a window by
-          // default. This menu item is re-interpreted as a single, toggle-able
-          // option to launch the hosted app as a tab.
-          AddCheckItemWithStringId(LAUNCH_TYPE_WINDOW,
-                                   IDS_APP_CONTEXT_MENU_OPEN_WINDOW);
-        } else {
-          AddCheckItemWithStringId(
-              LAUNCH_TYPE_REGULAR_TAB,
-              IDS_APP_CONTEXT_MENU_OPEN_REGULAR);
-          AddCheckItemWithStringId(
-              LAUNCH_TYPE_PINNED_TAB,
-              IDS_APP_CONTEXT_MENU_OPEN_PINNED);
-          AddCheckItemWithStringId(
-              LAUNCH_TYPE_WINDOW,
-              IDS_APP_CONTEXT_MENU_OPEN_WINDOW);
-          // Even though the launch type is Full Screen it is more accurately
-          // described as Maximized in Ash.
-          AddCheckItemWithStringId(
-              LAUNCH_TYPE_FULLSCREEN,
-              IDS_APP_CONTEXT_MENU_OPEN_MAXIMIZED);
-        }
-      }
-    } else if (item_.type == ash::TYPE_BROWSER_SHORTCUT) {
-      AddItem(MENU_NEW_WINDOW,
-              l10n_util::GetStringUTF16(IDS_APP_LIST_NEW_WINDOW));
-      if (!controller_->IsLoggedInAsGuest()) {
-        AddItem(MENU_NEW_INCOGNITO_WINDOW,
-                l10n_util::GetStringUTF16(IDS_APP_LIST_NEW_INCOGNITO_WINDOW));
-      }
-    } else if (item_.type == ash::TYPE_DIALOG) {
-      AddItem(MENU_CLOSE,
-              l10n_util::GetStringUTF16(IDS_LAUNCHER_CONTEXT_MENU_CLOSE));
-    } else {
-      if (item_.type == ash::TYPE_PLATFORM_APP) {
-        AddItem(
-            MENU_PIN,
-            l10n_util::GetStringUTF16(IDS_LAUNCHER_CONTEXT_MENU_PIN));
-      }
-      bool show_close_button = controller_->IsOpen(item_.id);
-#if defined(OS_CHROMEOS)
-      if (extension_misc::IsImeMenuExtensionId(
-              controller_->GetAppIDForShelfID(item_.id))) {
-        show_close_button = false;
-      }
-#endif
-      if (show_close_button) {
-        AddItem(MENU_CLOSE,
-                l10n_util::GetStringUTF16(IDS_LAUNCHER_CONTEXT_MENU_CLOSE));
-      }
-    }
-    AddSeparator(ui::NORMAL_SEPARATOR);
-    if (item_.type == ash::TYPE_APP_SHORTCUT ||
-        item_.type == ash::TYPE_WINDOWED_APP ||
-        item_.type == ash::TYPE_PLATFORM_APP) {
-      const extensions::MenuItem::ExtensionKey app_key(
-          controller_->GetAppIDForShelfID(item_.id));
-      if (!app_key.empty()) {
-        int index = 0;
-        extension_items_->AppendExtensionItems(app_key,
-                                               base::string16(),
-                                               &index,
-                                               false);  // is_action_menu
-        AddSeparator(ui::NORMAL_SEPARATOR);
-      }
-    }
-  }
-  // In fullscreen, the launcher is either hidden or autohidden depending on the
-  // type of fullscreen. Do not show the auto-hide menu item while in fullscreen
-  // because it is confusing when the preference appears not to apply.
-  if (!IsFullScreenMode() &&
-      CanUserModifyShelfAutoHideBehavior(controller_->profile())) {
-    AddCheckItemWithStringId(MENU_AUTO_HIDE,
-                             IDS_ASH_SHELF_CONTEXT_MENU_AUTO_HIDE);
-  }
-  if (ash::ShelfWidget::ShelfAlignmentAllowed() &&
-      !ash::Shell::GetInstance()->session_state_delegate()->IsScreenLocked()) {
-    AddSubMenuWithStringId(MENU_ALIGNMENT_MENU,
-                           IDS_ASH_SHELF_CONTEXT_MENU_POSITION,
-                           &shelf_alignment_menu_);
-  }
-#if defined(OS_CHROMEOS)
-  if (!controller_->IsLoggedInAsGuest()) {
-    AddItem(MENU_CHANGE_WALLPAPER,
-            l10n_util::GetStringUTF16(IDS_AURA_SET_DESKTOP_WALLPAPER));
-  }
-#endif
 }
 
 LauncherContextMenu::~LauncherContextMenu() {
 }
 
 bool LauncherContextMenu::IsItemForCommandIdDynamic(int command_id) const {
-  return command_id == MENU_OPEN_NEW;
+  return false;
 }
 
 base::string16 LauncherContextMenu::GetLabelForCommandId(int command_id) const {
-  if (command_id == MENU_OPEN_NEW) {
-    if (item_.type == ash::TYPE_PLATFORM_APP) {
-      return l10n_util::GetStringUTF16(IDS_APP_LIST_CONTEXT_MENU_NEW_WINDOW);
-    }
-    switch (controller_->GetLaunchType(item_.id)) {
-      case extensions::LAUNCH_TYPE_PINNED:
-      case extensions::LAUNCH_TYPE_REGULAR:
-        return l10n_util::GetStringUTF16(IDS_APP_LIST_CONTEXT_MENU_NEW_TAB);
-      case extensions::LAUNCH_TYPE_FULLSCREEN:
-      case extensions::LAUNCH_TYPE_WINDOW:
-        return l10n_util::GetStringUTF16(IDS_APP_LIST_CONTEXT_MENU_NEW_WINDOW);
-      default:
-        NOTREACHED();
-        return base::string16();
-    }
-  }
   NOTREACHED();
   return base::string16();
 }
 
 bool LauncherContextMenu::IsCommandIdChecked(int command_id) const {
-  switch (command_id) {
-    case LAUNCH_TYPE_PINNED_TAB:
-      return controller_->GetLaunchType(item_.id) ==
-          extensions::LAUNCH_TYPE_PINNED;
-    case LAUNCH_TYPE_REGULAR_TAB:
-      return controller_->GetLaunchType(item_.id) ==
-          extensions::LAUNCH_TYPE_REGULAR;
-    case LAUNCH_TYPE_WINDOW:
-      return controller_->GetLaunchType(item_.id) ==
-          extensions::LAUNCH_TYPE_WINDOW;
-    case LAUNCH_TYPE_FULLSCREEN:
-      return controller_->GetLaunchType(item_.id) ==
-          extensions::LAUNCH_TYPE_FULLSCREEN;
-    case MENU_AUTO_HIDE:
-      return shelf_->GetAutoHideBehavior() ==
-             ash::SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS;
-    default:
-      if (command_id < MENU_ITEM_COUNT)
-        return false;
-      return (extension_items_ &&
-              extension_items_->IsCommandIdChecked(command_id));
+  if (command_id == MENU_AUTO_HIDE) {
+    return shelf_->GetAutoHideBehavior() ==
+           ash::SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS;
   }
+  DCHECK(command_id < MENU_ITEM_COUNT);
+  return false;
 }
 
 bool LauncherContextMenu::IsCommandIdEnabled(int command_id) const {
@@ -233,23 +86,14 @@
     case MENU_PIN:
       return controller_->IsPinnable(item_.id);
     case MENU_CHANGE_WALLPAPER:
-      return ash::Shell::GetInstance()->user_wallpaper_delegate()->
-          CanOpenSetWallpaperPage();
-    case MENU_NEW_WINDOW:
-      // "Normal" windows are not allowed when incognito is enforced.
-      return IncognitoModePrefs::GetAvailability(
-          controller_->profile()->GetPrefs()) != IncognitoModePrefs::FORCED;
+      return ash::Shell::GetInstance()
+          ->user_wallpaper_delegate()
+          ->CanOpenSetWallpaperPage();
     case MENU_AUTO_HIDE:
       return CanUserModifyShelfAutoHideBehavior(controller_->profile());
-    case MENU_NEW_INCOGNITO_WINDOW:
-      // Incognito windows are not allowed when incognito is disabled.
-      return IncognitoModePrefs::GetAvailability(
-          controller_->profile()->GetPrefs()) != IncognitoModePrefs::DISABLED;
     default:
-      if (command_id < MENU_ITEM_COUNT)
-        return true;
-      return (extension_items_ &&
-              extension_items_->IsCommandIdEnabled(command_id));
+      DCHECK(command_id < MENU_ITEM_COUNT);
+      return true;
   }
 }
 
@@ -282,40 +126,12 @@
     case MENU_PIN:
       controller_->TogglePinned(item_.id);
       break;
-    case LAUNCH_TYPE_PINNED_TAB:
-      controller_->SetLaunchType(item_.id, extensions::LAUNCH_TYPE_PINNED);
-      break;
-    case LAUNCH_TYPE_REGULAR_TAB:
-      controller_->SetLaunchType(item_.id, extensions::LAUNCH_TYPE_REGULAR);
-      break;
-    case LAUNCH_TYPE_WINDOW: {
-      extensions::LaunchType launch_type = extensions::LAUNCH_TYPE_WINDOW;
-      // With bookmark apps enabled, hosted apps can only toggle between
-      // LAUNCH_WINDOW and LAUNCH_REGULAR.
-      if (extensions::util::IsNewBookmarkAppsEnabled()) {
-        launch_type = controller_->GetLaunchType(item_.id) ==
-                              extensions::LAUNCH_TYPE_WINDOW
-                          ? extensions::LAUNCH_TYPE_REGULAR
-                          : extensions::LAUNCH_TYPE_WINDOW;
-      }
-      controller_->SetLaunchType(item_.id, launch_type);
-      break;
-    }
-    case LAUNCH_TYPE_FULLSCREEN:
-      controller_->SetLaunchType(item_.id, extensions::LAUNCH_TYPE_FULLSCREEN);
-      break;
     case MENU_AUTO_HIDE:
       shelf_->SetAutoHideBehavior(shelf_->GetAutoHideBehavior() ==
                                           ash::SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS
                                       ? ash::SHELF_AUTO_HIDE_BEHAVIOR_NEVER
                                       : ash::SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS);
       break;
-    case MENU_NEW_WINDOW:
-      controller_->CreateNewWindow();
-      break;
-    case MENU_NEW_INCOGNITO_WINDOW:
-      controller_->CreateNewIncognitoWindow();
-      break;
     case MENU_ALIGNMENT_MENU:
       break;
     case MENU_CHANGE_WALLPAPER:
@@ -323,9 +139,58 @@
           OpenSetWallpaperPage();
       break;
     default:
-      if (extension_items_) {
-        extension_items_->ExecuteCommand(command_id, nullptr, nullptr,
-                                         content::ContextMenuParams());
-      }
+      NOTREACHED();
+  }
+}
+
+void LauncherContextMenu::AddPinMenu() {
+  // Expect an item with a none zero id to add pin/unpin menu item.
+  DCHECK(item_.id);
+  const std::string app_id = controller_->GetAppIDForShelfID(item_.id);
+  int menu_pin_string_id;
+  if (!controller_->CanPin(app_id))
+    menu_pin_string_id = IDS_LAUNCHER_CONTEXT_MENU_PIN_ENFORCED_BY_POLICY;
+  else if (controller_->IsPinned(item_.id))
+    menu_pin_string_id = IDS_LAUNCHER_CONTEXT_MENU_UNPIN;
+  else
+    menu_pin_string_id = IDS_LAUNCHER_CONTEXT_MENU_PIN;
+  AddItemWithStringId(MENU_PIN, menu_pin_string_id);
+}
+
+void LauncherContextMenu::AddShelfOptionsMenu() {
+  // In fullscreen, the launcher is either hidden or autohidden depending
+  // on thethe type of fullscreen. Do not show the auto-hide menu item while in
+  // while in fullscreen because it is confusing when the preference appears
+  // not to apply.
+  if (!IsFullScreenMode() &&
+      CanUserModifyShelfAutoHideBehavior(controller_->profile())) {
+    AddCheckItemWithStringId(MENU_AUTO_HIDE,
+                             IDS_ASH_SHELF_CONTEXT_MENU_AUTO_HIDE);
+  }
+  if (ash::ShelfWidget::ShelfAlignmentAllowed() &&
+      !ash::Shell::GetInstance()->session_state_delegate()->IsScreenLocked()) {
+    AddSubMenuWithStringId(MENU_ALIGNMENT_MENU,
+                           IDS_ASH_SHELF_CONTEXT_MENU_POSITION,
+                           &shelf_alignment_menu_);
+  }
+#if defined(OS_CHROMEOS)
+  if (!controller_->IsLoggedInAsGuest())
+    AddItemWithStringId(MENU_CHANGE_WALLPAPER, IDS_AURA_SET_DESKTOP_WALLPAPER);
+#endif
+}
+
+bool LauncherContextMenu::ExecuteCommonCommand(int command_id,
+                                               int event_flags) {
+  switch (command_id) {
+    case MENU_OPEN_NEW:
+    case MENU_CLOSE:
+    case MENU_PIN:
+    case MENU_AUTO_HIDE:
+    case MENU_ALIGNMENT_MENU:
+    case MENU_CHANGE_WALLPAPER:
+      ExecuteCommand(command_id, event_flags);
+      return true;
+    default:
+      return false;
   }
 }
diff --git a/chrome/browser/ui/ash/launcher/launcher_context_menu.h b/chrome/browser/ui/ash/launcher/launcher_context_menu.h
index f7006c9..905e6b3 100644
--- a/chrome/browser/ui/ash/launcher/launcher_context_menu.h
+++ b/chrome/browser/ui/ash/launcher/launcher_context_menu.h
@@ -9,25 +9,26 @@
 #include "ash/shelf/shelf_item_types.h"
 #include "base/gtest_prod_util.h"
 #include "base/macros.h"
-#include "base/memory/scoped_ptr.h"
 #include "ui/base/models/simple_menu_model.h"
 
 class ChromeLauncherController;
 
-namespace extensions {
-class ContextMenuMatcher;
+namespace ash {
+class Shelf;
 }
 
-// Context menu shown for the ash shell desktop, or for an item in the shelf.
+// Base class for context menu which is shown for a regular extension item in
+// the shelf, or for an Arc app item in the shelf, or shown when right click
+// on desktop shell.
 class LauncherContextMenu : public ui::SimpleMenuModel,
                             public ui::SimpleMenuModel::Delegate {
  public:
-  LauncherContextMenu(ChromeLauncherController* controller,
-                      const ash::ShelfItem* item,
-                      ash::Shelf* shelf);
   ~LauncherContextMenu() override;
 
-  void Init();
+  // Static function to create contextmenu instance.
+  static LauncherContextMenu* Create(ChromeLauncherController* controller,
+                                     const ash::ShelfItem* item,
+                                     ash::Shelf* shelf);
 
   // ui::SimpleMenuModel::Delegate overrides:
   bool IsItemForCommandIdDynamic(int command_id) const override;
@@ -38,17 +39,7 @@
                                   ui::Accelerator* accelerator) override;
   void ExecuteCommand(int command_id, int event_flags) override;
 
- private:
-  FRIEND_TEST_ALL_PREFIXES(
-      LauncherContextMenuTest,
-      NewIncognitoWindowMenuIsDisabledWhenIncognitoModeOff);
-  FRIEND_TEST_ALL_PREFIXES(
-      LauncherContextMenuTest,
-      NewWindowMenuIsDisabledWhenIncognitoModeForced);
-  FRIEND_TEST_ALL_PREFIXES(
-      LauncherContextMenuTest,
-      AutoHideOptionInMaximizedMode);
-
+ protected:
   enum MenuItem {
     MENU_OPEN_NEW,
     MENU_CLOSE,
@@ -65,14 +56,44 @@
     MENU_ITEM_COUNT
   };
 
+  LauncherContextMenu(ChromeLauncherController* controller,
+                      const ash::ShelfItem* item,
+                      ash::Shelf* shelf);
+  ChromeLauncherController* controller() const { return controller_; }
+
+  const ash::ShelfItem& item() const { return item_; }
+
+  ash::Shelf* shelf() const { return shelf_; }
+
+  // Add menu item for pin/unpin.
+  void AddPinMenu();
+
+  // Add common shelf options items, e.g. autohide mode, alignment and
+  // setting wallpaper.
+  void AddShelfOptionsMenu();
+
+  // Helper method to execute common commands. Returns true if handled.
+  bool ExecuteCommonCommand(int command_id, int event_flags);
+
+ private:
+  FRIEND_TEST_ALL_PREFIXES(
+      LauncherContextMenuTest,
+      NewIncognitoWindowMenuIsDisabledWhenIncognitoModeOff);
+  FRIEND_TEST_ALL_PREFIXES(LauncherContextMenuTest,
+                           NewWindowMenuIsDisabledWhenIncognitoModeForced);
+  FRIEND_TEST_ALL_PREFIXES(LauncherContextMenuTest,
+                           AutoHideOptionInMaximizedMode);
+  FRIEND_TEST_ALL_PREFIXES(LauncherContextMenuTest,
+                           DesktopShellLauncherContextMenuItemCheck);
+  FRIEND_TEST_ALL_PREFIXES(LauncherContextMenuTest,
+                           ArcLauncherContextMenuItemCheck);
+
   ChromeLauncherController* controller_;
 
   ash::ShelfItem item_;
 
   ash::ShelfAlignmentMenu shelf_alignment_menu_;
 
-  scoped_ptr<extensions::ContextMenuMatcher> extension_items_;
-
   ash::Shelf* shelf_;
 
   DISALLOW_COPY_AND_ASSIGN(LauncherContextMenu);
diff --git a/chrome/browser/ui/ash/launcher/launcher_context_menu_unittest.cc b/chrome/browser/ui/ash/launcher/launcher_context_menu_unittest.cc
index f41ae24..8a5b3f21 100644
--- a/chrome/browser/ui/ash/launcher/launcher_context_menu_unittest.cc
+++ b/chrome/browser/ui/ash/launcher/launcher_context_menu_unittest.cc
@@ -14,6 +14,8 @@
 #include "chrome/browser/prefs/incognito_mode_prefs.h"
 #include "chrome/browser/profiles/profile.h"
 #include "chrome/browser/ui/ash/launcher/chrome_launcher_controller.h"
+#include "chrome/browser/ui/ash/launcher/desktop_shell_launcher_context_menu.h"
+#include "chrome/browser/ui/ash/launcher/extension_launcher_context_menu.h"
 #include "chrome/test/base/testing_profile.h"
 #include "components/prefs/pref_service.h"
 #include "ui/aura/window_event_dispatcher.h"
@@ -42,7 +44,13 @@
     item.id = 1;  // dummy id
     item.type = shelf_item_type;
     ash::Shelf* shelf = ash::Shelf::ForWindow(CurrentContext());
-    return new LauncherContextMenu(controller_.get(), &item, shelf);
+    return LauncherContextMenu::Create(controller_.get(), &item, shelf);
+  }
+
+  LauncherContextMenu* CreateLauncherContextMenuForDesktopShell() {
+    ash::ShelfItem* item = nullptr;
+    ash::Shelf* shelf = ash::Shelf::ForWindow(CurrentContext());
+    return LauncherContextMenu::Create(controller_.get(), item, shelf);
   }
 
   Profile* profile() { return profile_.get(); }
@@ -97,3 +105,27 @@
       menu.get(), LauncherContextMenu::MENU_NEW_WINDOW));
   EXPECT_FALSE(menu->IsCommandIdEnabled(LauncherContextMenu::MENU_NEW_WINDOW));
 }
+
+// Verifies status of contextmenu items for desktop shell.
+TEST_F(LauncherContextMenuTest, DesktopShellLauncherContextMenuItemCheck) {
+  scoped_ptr<LauncherContextMenu> menu(
+      CreateLauncherContextMenuForDesktopShell());
+  EXPECT_FALSE(
+      IsItemPresentInMenu(menu.get(), LauncherContextMenu::MENU_OPEN_NEW));
+  EXPECT_FALSE(IsItemPresentInMenu(menu.get(), LauncherContextMenu::MENU_PIN));
+  EXPECT_TRUE(
+      IsItemPresentInMenu(menu.get(), LauncherContextMenu::MENU_AUTO_HIDE));
+  EXPECT_TRUE(menu->IsCommandIdEnabled(LauncherContextMenu::MENU_AUTO_HIDE));
+  EXPECT_TRUE(IsItemPresentInMenu(menu.get(),
+                                  LauncherContextMenu::MENU_ALIGNMENT_MENU));
+  EXPECT_TRUE(
+      menu->IsCommandIdEnabled(LauncherContextMenu::MENU_ALIGNMENT_MENU));
+#if defined(OS_CHROMEOS)
+  // By default, screen is not locked and ChangeWallPaper item is added in
+  // menu. ChangeWallPaper item is not enabled in default mode.
+  EXPECT_TRUE(IsItemPresentInMenu(menu.get(),
+                                  LauncherContextMenu::MENU_CHANGE_WALLPAPER));
+  EXPECT_FALSE(
+      menu->IsCommandIdEnabled(LauncherContextMenu::MENU_CHANGE_WALLPAPER));
+#endif
+}
diff --git a/chrome/browser/ui/exclusive_access/fullscreen_controller.cc b/chrome/browser/ui/exclusive_access/fullscreen_controller.cc
index b341896..de79134 100644
--- a/chrome/browser/ui/exclusive_access/fullscreen_controller.cc
+++ b/chrome/browser/ui/exclusive_access/fullscreen_controller.cc
@@ -505,8 +505,9 @@
     return CONTENT_SETTING_ALLOW;
   }
 
-  // See the comment above the call to |SetContentSetting()| for how the
-  // requesting and embedding origins interact with each other wrt permissions.
+  // See the comment above the call to |SetContentSettingDefaultScope()| for how
+  // the requesting and embedding origins interact with each other wrt
+  // permissions.
   return HostContentSettingsMapFactory::GetForProfile(
       exclusive_access_manager()->context()->GetProfile())
           ->GetContentSetting(url, GetEmbeddingOrigin(),
diff --git a/chrome/browser/ui/webui/options/content_settings_handler.cc b/chrome/browser/ui/webui/options/content_settings_handler.cc
index 69c929d2..3a49edcb 100644
--- a/chrome/browser/ui/webui/options/content_settings_handler.cc
+++ b/chrome/browser/ui/webui/options/content_settings_handler.cc
@@ -1354,7 +1354,7 @@
       mode == "normal" ? GetContentSettingsMap() :
                          GetOTRContentSettingsMap();
   if (settings_map) {
-    settings_map->SetContentSetting(
+    settings_map->SetContentSettingCustomScope(
         ContentSettingsPattern::FromString(pattern),
         secondary_pattern.empty()
             ? ContentSettingsPattern::Wildcard()
@@ -1526,11 +1526,9 @@
         content_settings::ContentSettingFromString(setting, &setting_type);
     DCHECK(result);
 
-    settings_map->SetContentSetting(ContentSettingsPattern::FromString(pattern),
-                                    ContentSettingsPattern::Wildcard(),
-                                    type,
-                                    std::string(),
-                                    setting_type);
+    settings_map->SetContentSettingCustomScope(
+        ContentSettingsPattern::FromString(pattern),
+        ContentSettingsPattern::Wildcard(), type, std::string(), setting_type);
     WebSiteSettingsUmaUtil::LogPermissionChange(type, setting_type);
   }
 }
diff --git a/chrome/browser/ui/webui/plugins/plugins.mojom b/chrome/browser/ui/webui/plugins/plugins.mojom
index 5b82ffc..6e1ceb9 100644
--- a/chrome/browser/ui/webui/plugins/plugins.mojom
+++ b/chrome/browser/ui/webui/plugins/plugins.mojom
@@ -22,6 +22,7 @@
 
 struct PluginData {
   bool always_allowed;
+  bool trusted;
   string description;
   bool critical;
   string enabled_mode;
diff --git a/chrome/browser/ui/webui/plugins/plugins_handler.cc b/chrome/browser/ui/webui/plugins/plugins_handler.cc
index a37e602f..c607ae7 100644
--- a/chrome/browser/ui/webui/plugins/plugins_handler.cc
+++ b/chrome/browser/ui/webui/plugins/plugins_handler.cc
@@ -162,10 +162,12 @@
 void PluginsHandler::SetPluginAlwaysAllowed(const mojo::String& plugin,
                                             bool allowed) {
   Profile* profile = Profile::FromWebUI(web_ui_);
-  HostContentSettingsMapFactory::GetForProfile(profile)->SetContentSetting(
-      ContentSettingsPattern::Wildcard(), ContentSettingsPattern::Wildcard(),
-      CONTENT_SETTINGS_TYPE_PLUGINS, plugin.get(),
-      allowed ? CONTENT_SETTING_ALLOW : CONTENT_SETTING_DEFAULT);
+  HostContentSettingsMapFactory::GetForProfile(profile)
+      ->SetContentSettingCustomScope(
+          ContentSettingsPattern::Wildcard(),
+          ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_PLUGINS,
+          plugin.get(),
+          allowed ? CONTENT_SETTING_ALLOW : CONTENT_SETTING_DEFAULT);
 
   // Keep track of the whitelist separately, so that we can distinguish plugins
   // whitelisted by the user from automatically whitelisted ones.
@@ -258,11 +260,19 @@
         GetPluginGroupEnabledMode(plugin_files, group_enabled));
 
     plugin_data->always_allowed = false;
+    plugin_data->trusted = false;
+
     if (group_enabled) {
-      const base::DictionaryValue* whitelist =
-          profile->GetPrefs()->GetDictionary(
-              prefs::kContentSettingsPluginWhitelist);
-      whitelist->GetBoolean(group_identifier, &plugin_data->always_allowed);
+      if (plugin_metadata->GetSecurityStatus(*active_plugin) ==
+          PluginMetadata::SECURITY_STATUS_FULLY_TRUSTED) {
+        plugin_data->trusted = true;
+        plugin_data->always_allowed = true;
+      } else {
+        const base::DictionaryValue* whitelist =
+            profile->GetPrefs()->GetDictionary(
+                prefs::kContentSettingsPluginWhitelist);
+        whitelist->GetBoolean(group_identifier, &plugin_data->always_allowed);
+      }
     }
 
     plugin_data->critical = false;
diff --git a/chrome/browser/ui/webui/settings/site_settings_handler.cc b/chrome/browser/ui/webui/settings/site_settings_handler.cc
index 24c11c9..15d1e2a7 100644
--- a/chrome/browser/ui/webui/settings/site_settings_handler.cc
+++ b/chrome/browser/ui/webui/settings/site_settings_handler.cc
@@ -220,7 +220,7 @@
 
   HostContentSettingsMap* map =
       HostContentSettingsMapFactory::GetForProfile(profile_);
-  map->SetContentSetting(
+  map->SetContentSettingCustomScope(
       ContentSettingsPattern::FromString(primary_pattern),
       secondary_pattern.empty() ?
           ContentSettingsPattern::Wildcard() :
@@ -246,7 +246,7 @@
 
   HostContentSettingsMap* map =
       HostContentSettingsMapFactory::GetForProfile(profile_);
-  map->SetContentSetting(
+  map->SetContentSettingCustomScope(
       ContentSettingsPattern::FromString(primary_pattern),
       secondary_pattern.empty() ?
           ContentSettingsPattern::Wildcard() :
diff --git a/chrome/browser/web_bluetooth_browsertest.cc b/chrome/browser/web_bluetooth_browsertest.cc
index 6a94ea45..2692b61e 100644
--- a/chrome/browser/web_bluetooth_browsertest.cc
+++ b/chrome/browser/web_bluetooth_browsertest.cc
@@ -76,4 +76,32 @@
               testing::MatchesRegex("NotFoundError: .*globally disabled.*"));
 }
 
+// Tests that using Finch field trial parameters for blacklist additions has
+// the effect of rejecting requestDevice calls.
+IN_PROC_BROWSER_TEST_F(WebBluetoothTest, BlacklistShouldBlock) {
+  // Fake the BluetoothAdapter to say it's present.
+  scoped_refptr<device::MockBluetoothAdapter> adapter =
+      new testing::NiceMock<device::MockBluetoothAdapter>;
+  EXPECT_CALL(*adapter, IsPresent()).WillRepeatedly(testing::Return(true));
+  device::BluetoothAdapterFactory::SetAdapterForTesting(adapter);
+
+  std::map<std::string, std::string> params;
+  params["blacklist_additions"] = "ee01:e";
+  variations::AssociateVariationParams("WebBluetoothBlacklist", "TestGroup",
+                                       params);
+  base::FieldTrialList::CreateFieldTrial("WebBluetoothBlacklist", "TestGroup");
+
+  std::string rejection;
+  EXPECT_TRUE(content::ExecuteScriptAndExtractString(
+      web_contents_,
+      "navigator.bluetooth.requestDevice({filters: [{services: [0xee01]}]})"
+      "  .then(() => { domAutomationController.send('Success'); },"
+      "        reason => {"
+      "      domAutomationController.send(reason.name + ': ' + reason.message);"
+      "  });",
+      &rejection));
+  EXPECT_THAT(rejection,
+              testing::MatchesRegex("SecurityError: .*blacklisted UUID.*"));
+}
+
 }  // namespace
diff --git a/chrome/chrome.gyp b/chrome/chrome.gyp
index 235f087..f47e24c 100644
--- a/chrome/chrome.gyp
+++ b/chrome/chrome.gyp
@@ -585,8 +585,11 @@
             '../components/components_strings.gyp:components_strings',
             '../content/content.gyp:content_java',
             '../media/media.gyp:media_java',
+            '../mojo/mojo_public.gyp:mojo_bindings_java',
+            '../mojo/mojo_public.gyp:mojo_public_java',
             '../printing/printing.gyp:printing_java',
             '../sync/sync.gyp:sync_java',
+            '../third_party/WebKit/public/blink.gyp:android_mojo_bindings_java',
             '../third_party/android_data_chart/android_data_chart.gyp:android_data_chart_java',
             '../third_party/android_media/android_media.gyp:android_media_java',
             '../third_party/android_protobuf/android_protobuf.gyp:protobuf_nano_javalib',
diff --git a/chrome/chrome_browser.gypi b/chrome/chrome_browser.gypi
index 8518b43..ec73df5 100644
--- a/chrome/chrome_browser.gypi
+++ b/chrome/chrome_browser.gypi
@@ -865,6 +865,8 @@
       'browser/android/metrics/uma_utils.h',
       'browser/android/metrics/variations_session.cc',
       'browser/android/metrics/variations_session.h',
+      'browser/android/mojo/chrome_service_registrar_android.cc',
+      'browser/android/mojo/chrome_service_registrar_android.h',
       'browser/android/net/external_estimate_provider_android.cc',
       'browser/android/net/external_estimate_provider_android.h',
       'browser/android/ntp/most_visited_sites.cc',
@@ -1928,6 +1930,7 @@
       'android/java/src/org/chromium/chrome/browser/media/remote/RemoteMediaPlayerBridge.java',
       'android/java/src/org/chromium/chrome/browser/media/router/ChromeMediaRouter.java',
       'android/java/src/org/chromium/chrome/browser/media/router/ChromeMediaRouterDialogController.java',
+      'android/java/src/org/chromium/chrome/browser/mojo/ChromeServiceRegistrar.java',
       'android/java/src/org/chromium/chrome/browser/infobar/DownloadOverwriteInfoBar.java',
       'android/java/src/org/chromium/chrome/browser/infobar/TranslateInfoBar.java',
       'android/java/src/org/chromium/chrome/browser/metrics/UmaSessionStats.java',
diff --git a/chrome/chrome_browser_ui.gypi b/chrome/chrome_browser_ui.gypi
index 4e6905d..eae2a46 100644
--- a/chrome/chrome_browser_ui.gypi
+++ b/chrome/chrome_browser_ui.gypi
@@ -561,10 +561,14 @@
       'browser/ui/ash/launcher/chrome_launcher_app_menu_item_v2app.h',
       'browser/ui/ash/launcher/chrome_launcher_controller.cc',
       'browser/ui/ash/launcher/chrome_launcher_controller.h',
+      'browser/ui/ash/launcher/desktop_shell_launcher_context_menu.cc',
+      'browser/ui/ash/launcher/desktop_shell_launcher_context_menu.h',
       'browser/ui/ash/launcher/extension_app_window_launcher_controller.cc',
       'browser/ui/ash/launcher/extension_app_window_launcher_controller.h',
       'browser/ui/ash/launcher/extension_app_window_launcher_item_controller.cc',
       'browser/ui/ash/launcher/extension_app_window_launcher_item_controller.h',
+      'browser/ui/ash/launcher/extension_launcher_context_menu.cc',
+      'browser/ui/ash/launcher/extension_launcher_context_menu.h',
       'browser/ui/ash/launcher/launcher_app_tab_helper.cc',
       'browser/ui/ash/launcher/launcher_app_tab_helper.h',
       'browser/ui/ash/launcher/launcher_app_updater.cc',
diff --git a/chrome/third_party/chromevox/chromevox/injected/mathjax_external_util.js b/chrome/third_party/chromevox/chromevox/injected/mathjax_external_util.js
index 29a79be7..051789b 100644
--- a/chrome/third_party/chromevox/chromevox/injected/mathjax_external_util.js
+++ b/chrome/third_party/chromevox/chromevox/injected/mathjax_external_util.js
@@ -251,8 +251,9 @@
 cvox.MathJaxExternalUtil.injectLoadScript = function() {
   var script = document.createElement('script');
   script.setAttribute('type', 'text/javascript');
+  var protocol = location.protocol == 'https:' ? 'https' : 'http';
   script.setAttribute(
-      'src', 'http://cdn.mathjax.org/mathjax/latest/MathJax.js');
+      'src', protocol + '://cdn.mathjax.org/mathjax/latest/MathJax.js');
   document.activeElement.appendChild(script);
 };
 
diff --git a/chromeos/CHROMEOS_LKGM b/chromeos/CHROMEOS_LKGM
index e9bab927..b56b22b0 100644
--- a/chromeos/CHROMEOS_LKGM
+++ b/chromeos/CHROMEOS_LKGM
@@ -1 +1 @@
-8121.0.0
\ No newline at end of file
+8157.0.0
\ No newline at end of file
diff --git a/components/bitmap_uploader/bitmap_uploader.cc b/components/bitmap_uploader/bitmap_uploader.cc
index d654742..2437c4c 100644
--- a/components/bitmap_uploader/bitmap_uploader.cc
+++ b/components/bitmap_uploader/bitmap_uploader.cc
@@ -39,8 +39,7 @@
       height_(0),
       format_(BGRA),
       next_resource_id_(1u),
-      id_namespace_(0u),
-      surface_client_binding_(this) {}
+      id_namespace_(0u) {}
 
 BitmapUploader::~BitmapUploader() {
   MojoGLES2DestroyContext(gles2_context_);
@@ -49,6 +48,7 @@
 void BitmapUploader::Init(mojo::Connector* connector) {
   surface_ = window_->RequestSurface(mus::mojom::SurfaceType::DEFAULT);
   surface_->BindToThread();
+  surface_->set_client(this);
 
   connector->ConnectToInterface("mojo:mus", &gpu_service_);
   mus::mojom::CommandBufferPtr gles2_client;
@@ -231,7 +231,8 @@
     Upload();
 }
 
-void BitmapUploader::ReturnResources(
+void BitmapUploader::OnResourcesReturned(
+    mus::WindowSurface* surface,
     mojo::Array<mus::mojom::ReturnedResourcePtr> resources) {
   MojoGLES2MakeCurrent(gles2_context_);
   // TODO(jamesr): Recycle.
diff --git a/components/bitmap_uploader/bitmap_uploader.h b/components/bitmap_uploader/bitmap_uploader.h
index 65162ac..48efe00 100644
--- a/components/bitmap_uploader/bitmap_uploader.h
+++ b/components/bitmap_uploader/bitmap_uploader.h
@@ -12,6 +12,7 @@
 #include "base/macros.h"
 #include "components/bitmap_uploader/bitmap_uploader_export.h"
 #include "components/mus/public/cpp/window_surface.h"
+#include "components/mus/public/cpp/window_surface_client.h"
 #include "components/mus/public/interfaces/compositor_frame.mojom.h"
 #include "components/mus/public/interfaces/gpu.mojom.h"
 #include "gpu/GLES2/gl2chromium.h"
@@ -29,7 +30,7 @@
 // BitmapUploader is useful if you want to draw a bitmap or color in a
 // mus::Window.
 class BITMAP_UPLOADER_EXPORT BitmapUploader
-    : NON_EXPORTED_BASE(public mus::mojom::SurfaceClient) {
+    : public NON_EXPORTED_BASE(mus::WindowSurfaceClient) {
  public:
   explicit BitmapUploader(mus::Window* window);
   ~BitmapUploader() override;
@@ -61,8 +62,9 @@
 
   void SetIdNamespace(uint32_t id_namespace);
 
-  // SurfaceClient implementation.
-  void ReturnResources(
+  // WindowSurfaceClient implementation.
+  void OnResourcesReturned(
+      mus::WindowSurface* surface,
       mojo::Array<mus::mojom::ReturnedResourcePtr> resources) override;
 
   mus::Window* window_;
@@ -79,7 +81,6 @@
   uint32_t next_resource_id_;
   uint32_t id_namespace_;
   base::hash_map<uint32_t, uint32_t> resource_to_texture_id_map_;
-  mojo::Binding<mus::mojom::SurfaceClient> surface_client_binding_;
 
   DISALLOW_COPY_AND_ASSIGN(BitmapUploader);
 };
diff --git a/components/content_settings/core/browser/cookie_settings_unittest.cc b/components/content_settings/core/browser/cookie_settings_unittest.cc
index c1d0ef7..77560e1 100644
--- a/components/content_settings/core/browser/cookie_settings_unittest.cc
+++ b/components/content_settings/core/browser/cookie_settings_unittest.cc
@@ -137,7 +137,7 @@
   prefs_.SetBoolean(prefs::kBlockThirdPartyCookies, true);
   // As an example for a url that matches all hosts but not all origins,
   // match all HTTPS sites.
-  settings_map_->SetContentSetting(
+  settings_map_->SetContentSettingCustomScope(
       kAllHttpsSitesPattern, ContentSettingsPattern::Wildcard(),
       CONTENT_SETTINGS_TYPE_COOKIES, std::string(), CONTENT_SETTING_ALLOW);
   cookie_settings_->SetDefaultCookieSetting(CONTENT_SETTING_SESSION_ONLY);
diff --git a/components/content_settings/core/browser/host_content_settings_map.cc b/components/content_settings/core/browser/host_content_settings_map.cc
index 5307adea..978aff41 100644
--- a/components/content_settings/core/browser/host_content_settings_map.cc
+++ b/components/content_settings/core/browser/host_content_settings_map.cc
@@ -387,11 +387,11 @@
       narrow_secondary = info.secondary_pattern;
   }
 
-  SetContentSetting(narrow_primary, narrow_secondary, type, std::string(),
-                    setting);
+  SetContentSettingCustomScope(narrow_primary, narrow_secondary, type,
+                               std::string(), setting);
 }
 
-void HostContentSettingsMap::SetContentSetting(
+void HostContentSettingsMap::SetContentSettingCustomScope(
     const ContentSettingsPattern& primary_pattern,
     const ContentSettingsPattern& secondary_pattern,
     ContentSettingsType content_type,
@@ -437,8 +437,8 @@
   if (!primary_pattern.IsValid() || !secondary_pattern.IsValid())
     return;
 
-  SetContentSetting(primary_pattern, secondary_pattern, content_type,
-                    resource_identifier, setting);
+  SetContentSettingCustomScope(primary_pattern, secondary_pattern, content_type,
+                               resource_identifier, setting);
 }
 
 void HostContentSettingsMap::MigrateOldSettings() {
@@ -476,7 +476,7 @@
           content_setting = GetContentSetting(url, url, type, std::string());
         }
         // Remove the old pattern.
-        SetContentSetting(setting_entry.primary_pattern,
+        SetContentSettingCustomScope(setting_entry.primary_pattern,
                           setting_entry.secondary_pattern, type, std::string(),
                           CONTENT_SETTING_DEFAULT);
         // Set the new pattern.
diff --git a/components/content_settings/core/browser/host_content_settings_map.h b/components/content_settings/core/browser/host_content_settings_map.h
index 7a75222a41..17d9e12 100644
--- a/components/content_settings/core/browser/host_content_settings_map.h
+++ b/components/content_settings/core/browser/host_content_settings_map.h
@@ -142,11 +142,12 @@
   // data types please use the method SetWebsiteSettingDefaultScope().
   //
   // This should only be called on the UI thread.
-  void SetContentSetting(const ContentSettingsPattern& primary_pattern,
-                         const ContentSettingsPattern& secondary_pattern,
-                         ContentSettingsType content_type,
-                         const std::string& resource_identifier,
-                         ContentSetting setting);
+  void SetContentSettingCustomScope(
+      const ContentSettingsPattern& primary_pattern,
+      const ContentSettingsPattern& secondary_pattern,
+      ContentSettingsType content_type,
+      const std::string& resource_identifier,
+      ContentSetting setting);
 
   // Sets the content |setting| for the default scope of the url that is
   // appropriate for the given |content_type| and |resource_identifier|.
@@ -159,10 +160,10 @@
   //
   // This should only be called on the UI thread.
   //
-  // Internally this will call SetContentSetting() with the default scope
-  // patterns for the given |content_type|. Developers will generally want
-  // to use this function instead of SetContentSetting() unless they need
-  // to specify custom scoping.
+  // Internally this will call SetContentSettingCustomScope() with the default
+  // scope patterns for the given |content_type|. Developers will generally want
+  // to use this function instead of SetContentSettingCustomScope() unless they
+  // need to specify custom scoping.
   void SetContentSettingDefaultScope(const GURL& primary_url,
                                      const GURL& secondary_url,
                                      ContentSettingsType content_type,
diff --git a/components/exo/wayland/server.cc b/components/exo/wayland/server.cc
index 9dfa9d3..52727be 100644
--- a/components/exo/wayland/server.cc
+++ b/components/exo/wayland/server.cc
@@ -49,6 +49,7 @@
 #include "ui/events/keycodes/dom/keycode_converter.h"
 #include "ui/gfx/display_observer.h"
 #include "ui/views/widget/widget.h"
+#include "ui/views/widget/widget_observer.h"
 
 #if defined(USE_OZONE)
 #include <drm_fourcc.h>
@@ -765,6 +766,37 @@
 ////////////////////////////////////////////////////////////////////////////////
 // wl_shell_surface_interface:
 
+class ShellSurfaceSizeObserver : public views::WidgetObserver {
+ public:
+  ShellSurfaceSizeObserver(wl_resource* shell_surface_resource,
+                           const gfx::Size& initial_size)
+      : shell_surface_resource_(shell_surface_resource),
+        old_size_(initial_size) {
+    wl_shell_surface_send_configure(shell_surface_resource,
+                                    WL_SHELL_SURFACE_RESIZE_NONE,
+                                    old_size_.width(), old_size_.height());
+  }
+
+  // Overridden from view::WidgetObserver:
+  void OnWidgetDestroyed(views::Widget* widget) override { delete this; }
+  void OnWidgetBoundsChanged(views::Widget* widget,
+                             const gfx::Rect& new_bounds) override {
+    if (old_size_ == new_bounds.size())
+      return;
+
+    wl_shell_surface_send_configure(shell_surface_resource_,
+                                    WL_SHELL_SURFACE_RESIZE_NONE,
+                                    new_bounds.width(), new_bounds.height());
+    old_size_ = new_bounds.size();
+  }
+
+ private:
+  wl_resource* shell_surface_resource_;
+  gfx::Size old_size_;
+
+  DISALLOW_COPY_AND_ASSIGN(ShellSurfaceSizeObserver);
+};
+
 void shell_surface_pong(wl_client* client,
                         wl_resource* resource,
                         uint32_t serial) {
@@ -804,13 +836,16 @@
                                   uint32_t method,
                                   uint32_t framerate,
                                   wl_resource* output_resource) {
-  GetUserDataAs<ShellSurface>(resource)->SetEnabled(true);
-  GetUserDataAs<ShellSurface>(resource)->SetFullscreen(true);
-  gfx::Rect bounds = GetUserDataAs<ShellSurface>(resource)
-                         ->GetWidget()
-                         ->GetWindowBoundsInScreen();
-  wl_shell_surface_send_configure(resource, WL_SHELL_SURFACE_RESIZE_NONE,
-                                  bounds.width(), bounds.height());
+  ShellSurface* shell_surface = GetUserDataAs<ShellSurface>(resource);
+  if (shell_surface->enabled())
+    return;
+
+  shell_surface->SetEnabled(true);
+  shell_surface->SetFullscreen(true);
+
+  views::Widget* widget = shell_surface->GetWidget();
+  widget->AddObserver(new ShellSurfaceSizeObserver(
+      resource, widget->GetWindowBoundsInScreen().size()));
 }
 
 void shell_surface_set_popup(wl_client* client,
@@ -827,13 +862,16 @@
 void shell_surface_set_maximized(wl_client* client,
                                  wl_resource* resource,
                                  wl_resource* output_resource) {
-  GetUserDataAs<ShellSurface>(resource)->SetEnabled(true);
-  GetUserDataAs<ShellSurface>(resource)->Maximize();
-  gfx::Rect bounds = GetUserDataAs<ShellSurface>(resource)
-                         ->GetWidget()
-                         ->GetWindowBoundsInScreen();
-  wl_shell_surface_send_configure(resource, WL_SHELL_SURFACE_RESIZE_NONE,
-                                  bounds.width(), bounds.height());
+  ShellSurface* shell_surface = GetUserDataAs<ShellSurface>(resource);
+  if (shell_surface->enabled())
+    return;
+
+  shell_surface->SetEnabled(true);
+  shell_surface->Maximize();
+
+  views::Widget* widget = shell_surface->GetWidget();
+  widget->AddObserver(new ShellSurfaceSizeObserver(
+      resource, widget->GetWindowBoundsInScreen().size()));
 }
 
 void shell_surface_set_title(wl_client* client,
diff --git a/components/mus/gles2/mojo_gpu_memory_buffer_manager.cc b/components/mus/gles2/mojo_gpu_memory_buffer_manager.cc
index 1f5c0845..08d9a38 100644
--- a/components/mus/gles2/mojo_gpu_memory_buffer_manager.cc
+++ b/components/mus/gles2/mojo_gpu_memory_buffer_manager.cc
@@ -16,7 +16,8 @@
 scoped_ptr<gfx::GpuMemoryBuffer>
 MojoGpuMemoryBufferManager::AllocateGpuMemoryBuffer(const gfx::Size& size,
                                                     gfx::BufferFormat format,
-                                                    gfx::BufferUsage usage) {
+                                                    gfx::BufferUsage usage,
+                                                    int32_t surface_id) {
   return MojoGpuMemoryBufferImpl::Create(size, format, usage);
 }
 
diff --git a/components/mus/gles2/mojo_gpu_memory_buffer_manager.h b/components/mus/gles2/mojo_gpu_memory_buffer_manager.h
index 7d74b00..d7aae7be 100644
--- a/components/mus/gles2/mojo_gpu_memory_buffer_manager.h
+++ b/components/mus/gles2/mojo_gpu_memory_buffer_manager.h
@@ -19,7 +19,8 @@
   scoped_ptr<gfx::GpuMemoryBuffer> AllocateGpuMemoryBuffer(
       const gfx::Size& size,
       gfx::BufferFormat format,
-      gfx::BufferUsage usage) override;
+      gfx::BufferUsage usage,
+      int32_t surface_id) override;
   scoped_ptr<gfx::GpuMemoryBuffer> CreateGpuMemoryBufferFromHandle(
       const gfx::GpuMemoryBufferHandle& handle,
       const gfx::Size& size,
diff --git a/components/mus/public/cpp/lib/window.cc b/components/mus/public/cpp/lib/window.cc
index d9a45ae..022e8fe 100644
--- a/components/mus/public/cpp/lib/window.cc
+++ b/components/mus/public/cpp/lib/window.cc
@@ -234,7 +234,7 @@
 bool Window::IsDrawn() const {
   if (!visible_)
     return false;
-  return parent_ ? parent_->IsDrawn() : drawn_;
+  return parent_ ? parent_->IsDrawn() : parent_drawn_;
 }
 
 scoped_ptr<WindowSurface> Window::RequestSurface(mojom::SurfaceType type) {
@@ -505,7 +505,7 @@
       viewport_metrics_(CreateEmptyViewportMetrics()),
       visible_(false),
       cursor_id_(mojom::Cursor::CURSOR_NULL),
-      drawn_(false) {}
+      parent_drawn_(false) {}
 
 WindowTreeClientImpl* Window::tree_client() {
   return static_cast<WindowTreeClientImpl*>(connection_);
@@ -637,18 +637,18 @@
       OnWindowViewportMetricsChanged(this, old_metrics, new_metrics));
 }
 
-void Window::LocalSetDrawn(bool value) {
-  if (drawn_ == value)
+void Window::LocalSetParentDrawn(bool value) {
+  if (parent_drawn_ == value)
     return;
 
-  // As IsDrawn() is derived from |visible_| and |drawn_|, only send drawn
-  // notification is the value of IsDrawn() is really changing.
+  // As IsDrawn() is derived from |visible_| and |parent_drawn_|, only send
+  // drawn notification is the value of IsDrawn() is really changing.
   if (IsDrawn() == value) {
-    drawn_ = value;
+    parent_drawn_ = value;
     return;
   }
   FOR_EACH_OBSERVER(WindowObserver, observers_, OnWindowDrawnChanging(this));
-  drawn_ = value;
+  parent_drawn_ = value;
   FOR_EACH_OBSERVER(WindowObserver, observers_, OnWindowDrawnChanged(this));
 }
 
diff --git a/components/mus/public/cpp/lib/window_private.h b/components/mus/public/cpp/lib/window_private.h
index e042035f..3974a9da 100644
--- a/components/mus/public/cpp/lib/window_private.h
+++ b/components/mus/public/cpp/lib/window_private.h
@@ -35,8 +35,8 @@
 
   void set_visible(bool visible) { window_->visible_ = visible; }
 
-  void set_drawn(bool drawn) { window_->drawn_ = drawn; }
-  bool drawn() { return window_->drawn_; }
+  void set_parent_drawn(bool drawn) { window_->parent_drawn_ = drawn; }
+  bool parent_drawn() { return window_->parent_drawn_; }
 
   void set_id(Id id) { window_->id_ = id; }
 
@@ -75,7 +75,7 @@
       const std::vector<gfx::Rect>& additional_client_areas) {
     window_->LocalSetClientArea(client_area, additional_client_areas);
   }
-  void LocalSetDrawn(bool drawn) { window_->LocalSetDrawn(drawn); }
+  void LocalSetParentDrawn(bool drawn) { window_->LocalSetParentDrawn(drawn); }
   void LocalSetVisible(bool visible) { window_->LocalSetVisible(visible); }
   void LocalSetPredefinedCursor(mojom::Cursor cursor) {
     window_->LocalSetPredefinedCursor(cursor);
diff --git a/components/mus/public/cpp/lib/window_tree_client_impl.cc b/components/mus/public/cpp/lib/window_tree_client_impl.cc
index 4218528..e7255ab 100644
--- a/components/mus/public/cpp/lib/window_tree_client_impl.cc
+++ b/components/mus/public/cpp/lib/window_tree_client_impl.cc
@@ -43,7 +43,6 @@
   private_window.set_connection(client);
   private_window.set_id(window_data->window_id);
   private_window.set_visible(window_data->visible);
-  private_window.set_drawn(window_data->drawn);
   private_window.LocalSetViewportMetrics(mojom::ViewportMetrics(),
                                          *window_data->viewport_metrics);
   private_window.set_properties(
@@ -484,7 +483,8 @@
 void WindowTreeClientImpl::OnEmbedImpl(mojom::WindowTree* window_tree,
                                        ConnectionSpecificId connection_id,
                                        mojom::WindowDataPtr root_data,
-                                       Id focused_window_id) {
+                                       Id focused_window_id,
+                                       bool drawn) {
   // WARNING: this is only called if WindowTreeClientImpl was created as the
   // result of an embedding.
   tree_ = window_tree;
@@ -496,6 +496,8 @@
 
   focused_window_ = GetWindowById(focused_window_id);
 
+  WindowPrivate(root).LocalSetParentDrawn(drawn);
+
   delegate_->OnEmbed(root);
 
   if (focused_window_) {
@@ -538,7 +540,12 @@
 
 Window* WindowTreeClientImpl::NewTopLevelWindow(
     const Window::SharedProperties* properties) {
-  return NewWindowImpl(NewWindowType::TOP_LEVEL, properties);
+  Window* window = NewWindowImpl(NewWindowType::TOP_LEVEL, properties);
+  // Assume newly created top level windows are drawn by default, otherwise
+  // requests to focus will fail. We will get the real value in
+  // OnTopLevelCreated().
+  window->LocalSetParentDrawn(true);
+  return window;
 }
 
 ConnectionSpecificId WindowTreeClientImpl::GetConnectionId() {
@@ -560,7 +567,8 @@
 void WindowTreeClientImpl::OnEmbed(ConnectionSpecificId connection_id,
                                    mojom::WindowDataPtr root_data,
                                    mojom::WindowTreePtr tree,
-                                   Id focused_window_id) {
+                                   Id focused_window_id,
+                                   bool drawn) {
   DCHECK(!tree_ptr_);
   tree_ptr_ = std::move(tree);
   tree_ptr_.set_connection_error_handler([this]() { delete this; });
@@ -571,7 +579,7 @@
   }
 
   OnEmbedImpl(tree_ptr_.get(), connection_id, std::move(root_data),
-              focused_window_id);
+              focused_window_id, drawn);
 }
 
 void WindowTreeClientImpl::OnEmbeddedAppDisconnected(Id window_id) {
@@ -604,7 +612,8 @@
 }
 
 void WindowTreeClientImpl::OnTopLevelCreated(uint32_t change_id,
-                                             mojom::WindowDataPtr data) {
+                                             mojom::WindowDataPtr data,
+                                             bool drawn) {
   // The server ack'd the top level window we created and supplied the state
   // of the window at the time the server created it. For properties we do not
   // have changes in flight for we can update them immediately. For properties
@@ -624,7 +633,7 @@
 
   // Drawn state and ViewportMetrics always come from the server (they can't
   // be modified locally).
-  window_private.set_drawn(data->drawn);
+  window_private.LocalSetParentDrawn(drawn);
   window_private.LocalSetViewportMetrics(mojom::ViewportMetrics(),
                                          *data->viewport_metrics);
 
@@ -800,10 +809,11 @@
   WindowPrivate(window).LocalSetVisible(visible);
 }
 
-void WindowTreeClientImpl::OnWindowDrawnStateChanged(Id window_id, bool drawn) {
+void WindowTreeClientImpl::OnWindowParentDrawnStateChanged(Id window_id,
+                                                           bool drawn) {
   Window* window = GetWindowById(window_id);
   if (window)
-    WindowPrivate(window).LocalSetDrawn(drawn);
+    WindowPrivate(window).LocalSetParentDrawn(drawn);
 }
 
 void WindowTreeClientImpl::OnWindowSharedPropertyChanged(
diff --git a/components/mus/public/cpp/lib/window_tree_client_impl.h b/components/mus/public/cpp/lib/window_tree_client_impl.h
index 8ed19e3..a22ce57 100644
--- a/components/mus/public/cpp/lib/window_tree_client_impl.h
+++ b/components/mus/public/cpp/lib/window_tree_client_impl.h
@@ -156,7 +156,8 @@
   void OnEmbedImpl(mojom::WindowTree* window_tree,
                    ConnectionSpecificId connection_id,
                    mojom::WindowDataPtr root_data,
-                   Id focused_window_id);
+                   Id focused_window_id,
+                   bool drawn);
 
   // Overridden from WindowTreeConnection:
   void SetDeleteOnNoRoots(bool value) override;
@@ -175,12 +176,14 @@
   void OnEmbed(ConnectionSpecificId connection_id,
                mojom::WindowDataPtr root,
                mojom::WindowTreePtr tree,
-               Id focused_window_id) override;
+               Id focused_window_id,
+               bool drawn) override;
   void OnEmbeddedAppDisconnected(Id window_id) override;
   void OnUnembed(Id window_id) override;
   void OnLostCapture(Id window_id) override;
   void OnTopLevelCreated(uint32_t change_id,
-                         mojom::WindowDataPtr data) override;
+                         mojom::WindowDataPtr data,
+                         bool drawn) override;
   void OnWindowBoundsChanged(Id window_id,
                              mojo::RectPtr old_bounds,
                              mojo::RectPtr new_bounds) override;
@@ -206,7 +209,7 @@
                          mojom::OrderDirection direction) override;
   void OnWindowDeleted(Id window_id) override;
   void OnWindowVisibilityChanged(Id window_id, bool visible) override;
-  void OnWindowDrawnStateChanged(Id window_id, bool drawn) override;
+  void OnWindowParentDrawnStateChanged(Id window_id, bool drawn) override;
   void OnWindowSharedPropertyChanged(Id window_id,
                                      const mojo::String& name,
                                      mojo::Array<uint8_t> new_data) override;
diff --git a/components/mus/public/cpp/tests/window_tree_client_impl_unittest.cc b/components/mus/public/cpp/tests/window_tree_client_impl_unittest.cc
index 822354a8..f59ce56 100644
--- a/components/mus/public/cpp/tests/window_tree_client_impl_unittest.cc
+++ b/components/mus/public/cpp/tests/window_tree_client_impl_unittest.cc
@@ -70,12 +70,12 @@
     root_data->bounds = mojo::Rect::From(gfx::Rect());
     root_data->properties.SetToEmpty();
     root_data->visible = true;
-    root_data->drawn = true;
     root_data->viewport_metrics = mojom::ViewportMetrics::New();
     root_data->viewport_metrics->size_in_pixels =
         mojo::Size::From(gfx::Size(1000, 1000));
     root_data->viewport_metrics->device_pixel_ratio = 1;
-    tree_client_impl_->OnEmbedImpl(window_tree, 1, std::move(root_data), 0);
+    tree_client_impl_->OnEmbedImpl(window_tree, 1, std::move(root_data), 0,
+                                   true);
   }
 
  private:
@@ -517,6 +517,7 @@
   ASSERT_TRUE(root1);
   Window* root2 = setup.window_tree_connection()->NewTopLevelWindow(nullptr);
   ASSERT_TRUE(root2);
+  EXPECT_TRUE(WindowPrivate(root2).parent_drawn());
   ASSERT_NE(root2, root1);
   EXPECT_NE(root2->id(), root1->id());
   EXPECT_EQ(2u, setup.window_tree_connection()->GetRoots().size());
@@ -531,7 +532,10 @@
   mojom::WindowDataPtr data = mojom::WindowData::New();
   data->window_id = root2->id();
   data->viewport_metrics = mojom::ViewportMetrics::New();
-  setup.window_tree_client()->OnTopLevelCreated(change_id, std::move(data));
+  setup.window_tree_client()->OnTopLevelCreated(change_id, std::move(data),
+                                                false);
+
+  EXPECT_FALSE(WindowPrivate(root2).parent_drawn());
 
   // Should not be able to add a top level as a child of another window.
   root1->AddChild(root2);
@@ -565,8 +569,8 @@
   data->viewport_metrics->size_in_pixels = mojo::Size::From(gfx::Size(1, 2));
   data->bounds = mojo::Rect::From(gfx::Rect(1, 2, 3, 4));
   data->visible = true;
-  data->drawn = true;
-  setup.window_tree_client()->OnTopLevelCreated(change_id, std::move(data));
+  setup.window_tree_client()->OnTopLevelCreated(change_id, std::move(data),
+                                                true);
 
   // Make sure all the properties took.
   EXPECT_TRUE(root2->IsDrawn());
@@ -624,15 +628,14 @@
   data->viewport_metrics->size_in_pixels = mojo::Size::From(gfx::Size(1, 2));
   data->bounds = mojo::Rect::From(gfx::Rect(1, 2, 3, 4));
   data->visible = true;
-  data->drawn = true;
   data->properties["xx"] = mojo::Array<uint8_t>::From(std::string("server_xx"));
   data->properties["yy"] = mojo::Array<uint8_t>::From(std::string("server_yy"));
   setup.window_tree_client()->OnTopLevelCreated(new_window_in_flight_change_id,
-                                                std::move(data));
+                                                std::move(data), true);
 
   // The only value that should take effect is the property for 'yy' as it was
   // not in flight.
-  EXPECT_TRUE(WindowPrivate(root2).drawn());
+  EXPECT_TRUE(WindowPrivate(root2).parent_drawn());
   EXPECT_FALSE(root2->visible());
   EXPECT_EQ(gfx::Size(1, 2),
             root2->viewport_metrics().size_in_pixels.To<gfx::Size>());
@@ -702,7 +705,8 @@
   root2->Destroy();
   EXPECT_EQ(1u, setup.window_tree_connection()->GetRoots().size());
 
-  setup.window_tree_client()->OnTopLevelCreated(change_id, std::move(data));
+  setup.window_tree_client()->OnTopLevelCreated(change_id, std::move(data),
+                                                true);
   EXPECT_EQ(1u, setup.window_tree_connection()->GetRoots().size());
 }
 
diff --git a/components/mus/public/cpp/tests/window_unittest.cc b/components/mus/public/cpp/tests/window_unittest.cc
index dc51663..2160f98 100644
--- a/components/mus/public/cpp/tests/window_unittest.cc
+++ b/components/mus/public/cpp/tests/window_unittest.cc
@@ -116,7 +116,7 @@
   EXPECT_TRUE(w1.visible());
   EXPECT_FALSE(w1.IsDrawn());
 
-  WindowPrivate(&w1).set_drawn(true);
+  WindowPrivate(&w1).set_parent_drawn(true);
 
   TestWindow w11;
   w11.SetVisible(true);
diff --git a/components/mus/public/cpp/window.h b/components/mus/public/cpp/window.h
index 3737d40..73a0048 100644
--- a/components/mus/public/cpp/window.h
+++ b/components/mus/public/cpp/window.h
@@ -253,7 +253,7 @@
       const std::vector<gfx::Rect>& additional_client_areas);
   void LocalSetViewportMetrics(const mojom::ViewportMetrics& old_metrics,
                                const mojom::ViewportMetrics& new_metrics);
-  void LocalSetDrawn(bool drawn);
+  void LocalSetParentDrawn(bool drawn);
   void LocalSetVisible(bool visible);
   void LocalSetPredefinedCursor(mojom::Cursor cursor_id);
   void LocalSetSharedProperty(const std::string& name,
@@ -316,10 +316,9 @@
 
   SharedProperties properties_;
 
-  // Drawn state is derived from the visible state and the parent's visible
-  // state. This field is only used if the window has no parent (eg it's a
-  // root).
-  bool drawn_;
+  // Drawn state of our parent. This is only meaningful for root Windows, in
+  // which the parent Window isn't exposed to the client.
+  bool parent_drawn_;
 
   // Value struct to keep the name and deallocator for this property.
   // Key cannot be used for this purpose because it can be char* or
diff --git a/components/mus/public/cpp/window_surface_client.h b/components/mus/public/cpp/window_surface_client.h
index 64e50c1..22bde17 100644
--- a/components/mus/public/cpp/window_surface_client.h
+++ b/components/mus/public/cpp/window_surface_client.h
@@ -16,7 +16,7 @@
       mojo::Array<mojom::ReturnedResourcePtr> resources) = 0;
 
  protected:
-  ~WindowSurfaceClient() {}
+  virtual ~WindowSurfaceClient() {}
 };
 
 }  // namespace mus
diff --git a/components/mus/public/interfaces/window_tree.mojom b/components/mus/public/interfaces/window_tree.mojom
index 90bdec0..e01a925 100644
--- a/components/mus/public/interfaces/window_tree.mojom
+++ b/components/mus/public/interfaces/window_tree.mojom
@@ -26,11 +26,8 @@
   mojo.Rect bounds;
   map<string, array<uint8>> properties;
   // True if this window is visible. The window may not be drawn on screen (see
-  // drawn for specifics).
+  // OnWindowParentDrawnStateChanged() for details).
   bool visible;
-  // True if this window is drawn on screen. A window is drawn if attached to
-  // the root and all ancestors (including this window) are visible.
-  bool drawn;
   ViewportMetrics viewport_metrics;
 };
 
@@ -255,11 +252,13 @@
   // Invoked when the client application has been embedded at |root|.
   // See Embed() on WindowTree for more details. |tree| will be a handle back to
   // the window manager service, unless the connection is to the root connection
-  // in which case it will be null.
+  // in which case it will be null. |parent_drawn| is true if roots parent is
+  // drawn, see OnParentDrawnStateChanged() for details.
   OnEmbed(uint16 connection_id,
           WindowData root,
           WindowTree? tree,
-          uint32 focused_window);
+          uint32 focused_window,
+          bool parent_drawn);
 
   // Invoked when the application embedded at |window| is disconnected. In other
   // words the embedded app closes the connection to the server. This is called
@@ -275,7 +274,9 @@
   OnLostCapture(uint32 window);
 
   // Called in response to NewTopLevelWindow() successfully completing.
-  OnTopLevelCreated(uint32 change_id, WindowData data);
+  // |parent_drawn| is true if the parent of the window is drawn, see
+  // OnDrawnStateChanged() for details.
+  OnTopLevelCreated(uint32 change_id, WindowData data, bool parent_drawn);
 
   // Invoked when a window's bounds have changed.
   OnWindowBoundsChanged(uint32 window,
@@ -324,17 +325,17 @@
   // Invoked when the visibility of the specified window changes.
   OnWindowVisibilityChanged(uint32 window, bool visible);
 
-  // Invoked when a change to the visibility of |window| or one if it's
-  // ancestors is done such that the drawn state changes. This is only invoked
-  // for the top most window of a particular connection. For example, if you
-  // have the hierarchy: A -> B1 -> B2 (B2 is a child of B1 and B1 a child of
-  // A), B1/B2 are from connection 2 and A from connection 1 with all windows
-  // visible and drawn and the visiblity of A changes to false, then connection
-  // 2 is told the drawn state of B1 has changed (to false), but is not told
-  // anything about B2 as it's drawn state can be calculated from that of B1.
+  // Invoked when the drawn state of |window|'s parent changes. The drawn state
+  // is determined by the visibility of a Window and the Windows ancestors. A
+  // Window is drawn if all ancestors are visible, not drawn if any ancestor is
+  // hidden.
   //
-  // NOTE: This is not invoked if OnWindowVisibilityChanged() is invoked.
-  OnWindowDrawnStateChanged(uint32 window, bool drawn);
+  // The initial drawn state is communicated by way of OnTopLevelCreated() or
+  // OnEmbed().
+  //
+  // This function is only called for root Windows as the drawn state of all
+  // other windows can be determined from their parent.
+  OnWindowParentDrawnStateChanged(uint32 window, bool drawn);
 
   // Invoked when a window property is changed. If this change is a removal,
   // |new_data| is null.
diff --git a/components/mus/ws/test_change_tracker.cc b/components/mus/ws/test_change_tracker.cc
index aefa54e0..3e6e8b8 100644
--- a/components/mus/ws/test_change_tracker.cc
+++ b/components/mus/ws/test_change_tracker.cc
@@ -34,10 +34,19 @@
   return direction == mojom::OrderDirection::ABOVE ? "above" : "below";
 }
 
-std::string ChangeToDescription1(const Change& change) {
+enum class ChangeDescriptionType {
+  ONE,
+  TWO,
+};
+
+std::string ChangeToDescription(const Change& change,
+                                ChangeDescriptionType type) {
   switch (change.type) {
     case CHANGE_TYPE_EMBED:
-      return "OnEmbed";
+      if (type == ChangeDescriptionType::ONE)
+        return "OnEmbed";
+      return base::StringPrintf("OnEmbed drawn=%s",
+                                change.bool_value ? "true" : "false");
 
     case CHANGE_TYPE_EMBEDDED_APP_DISCONNECTED:
       return base::StringPrintf("OnEmbeddedAppDisconnected window=%s",
@@ -125,31 +134,41 @@
                                 change.bool_value ? "true" : "false");
 
     case CHANGE_TYPE_ON_TOP_LEVEL_CREATED:
-      return base::StringPrintf("TopLevelCreated id=%d window_id=%s",
+      return base::StringPrintf("TopLevelCreated id=%d window_id=%s drawn=%s",
                                 change.change_id,
-                                WindowIdToString(change.window_id).c_str());
+                                WindowIdToString(change.window_id).c_str(),
+                                change.bool_value ? "true" : "false");
   }
   return std::string();
 }
 
+std::string SingleChangeToDescriptionImpl(const std::vector<Change>& changes,
+                                          ChangeDescriptionType change_type) {
+  std::string result;
+  for (auto& change : changes) {
+    if (!result.empty())
+      result += "\n";
+    result += ChangeToDescription(change, change_type);
+  }
+  return result;
+}
+
 }  // namespace
 
 std::vector<std::string> ChangesToDescription1(
     const std::vector<Change>& changes) {
   std::vector<std::string> strings(changes.size());
   for (size_t i = 0; i < changes.size(); ++i)
-    strings[i] = ChangeToDescription1(changes[i]);
+    strings[i] = ChangeToDescription(changes[i], ChangeDescriptionType::ONE);
   return strings;
 }
 
 std::string SingleChangeToDescription(const std::vector<Change>& changes) {
-  std::string result;
-  for (auto& change : changes) {
-    if (!result.empty())
-      result += "\n";
-    result += ChangeToDescription1(change);
-  }
-  return result;
+  return SingleChangeToDescriptionImpl(changes, ChangeDescriptionType::ONE);
+}
+
+std::string SingleChangeToDescription2(const std::vector<Change>& changes) {
+  return SingleChangeToDescriptionImpl(changes, ChangeDescriptionType::TWO);
 }
 
 std::string SingleWindowDescription(const std::vector<TestWindow>& windows) {
@@ -175,7 +194,6 @@
   window.parent_id = data->parent_id;
   window.window_id = data->window_id;
   window.visible = data->visible;
-  window.drawn = data->drawn;
   window.properties =
       data->properties.To<std::map<std::string, std::vector<uint8_t>>>();
   return window;
@@ -207,10 +225,12 @@
 TestChangeTracker::~TestChangeTracker() {}
 
 void TestChangeTracker::OnEmbed(ConnectionSpecificId connection_id,
-                                mojom::WindowDataPtr root) {
+                                mojom::WindowDataPtr root,
+                                bool drawn) {
   Change change;
   change.type = CHANGE_TYPE_EMBED;
   change.connection_id = connection_id;
+  change.bool_value = drawn;
   change.windows.push_back(WindowDataToTestWindow(root));
   AddChange(change);
 }
@@ -320,7 +340,8 @@
   AddChange(change);
 }
 
-void TestChangeTracker::OnWindowDrawnStateChanged(Id window_id, bool drawn) {
+void TestChangeTracker::OnWindowParentDrawnStateChanged(Id window_id,
+                                                        bool drawn) {
   Change change;
   change.type = CHANGE_TYPE_NODE_DRAWN_STATE_CHANGED;
   change.window_id = window_id;
@@ -377,11 +398,13 @@
 }
 
 void TestChangeTracker::OnTopLevelCreated(uint32_t change_id,
-                                          mojom::WindowDataPtr window_data) {
+                                          mojom::WindowDataPtr window_data,
+                                          bool drawn) {
   Change change;
   change.type = CHANGE_TYPE_ON_TOP_LEVEL_CREATED;
   change.change_id = change_id;
   change.window_id = window_data->window_id;
+  change.bool_value = drawn;
   AddChange(change);
 }
 
@@ -405,9 +428,8 @@
 
 std::string TestWindow::ToString2() const {
   return base::StringPrintf(
-      "window=%s parent=%s visible=%s drawn=%s",
-      WindowIdToString(window_id).c_str(), WindowIdToString(parent_id).c_str(),
-      visible ? "true" : "false", drawn ? "true" : "false");
+      "window=%s parent=%s visible=%s", WindowIdToString(window_id).c_str(),
+      WindowIdToString(parent_id).c_str(), visible ? "true" : "false");
 }
 
 }  // namespace ws
diff --git a/components/mus/ws/test_change_tracker.h b/components/mus/ws/test_change_tracker.h
index 46103bc..4e5fc76 100644
--- a/components/mus/ws/test_change_tracker.h
+++ b/components/mus/ws/test_change_tracker.h
@@ -58,7 +58,6 @@
   Id parent_id;
   Id window_id;
   bool visible;
-  bool drawn;
   std::map<std::string, std::vector<uint8_t>> properties;
 };
 
@@ -94,6 +93,7 @@
 // Convenience for returning the description of the first item in |changes|.
 // Returns an empty string if |changes| has something other than one entry.
 std::string SingleChangeToDescription(const std::vector<Change>& changes);
+std::string SingleChangeToDescription2(const std::vector<Change>& changes);
 
 // Convenience for returning the description of the first item in |windows|.
 // Returns an empty string if |windows| has something other than one entry.
@@ -130,7 +130,9 @@
 
   // Each of these functions generate a Change. There is one per
   // WindowTreeClient function.
-  void OnEmbed(ConnectionSpecificId connection_id, mojom::WindowDataPtr root);
+  void OnEmbed(ConnectionSpecificId connection_id,
+               mojom::WindowDataPtr root,
+               bool drawn);
   void OnEmbeddedAppDisconnected(Id window_id);
   void OnUnembed(Id window_id);
   void OnLostCapture(Id window_id);
@@ -150,7 +152,7 @@
                          mojom::OrderDirection direction);
   void OnWindowDeleted(Id window_id);
   void OnWindowVisibilityChanged(Id window_id, bool visible);
-  void OnWindowDrawnStateChanged(Id window_id, bool drawn);
+  void OnWindowParentDrawnStateChanged(Id window_id, bool drawn);
   void OnWindowInputEvent(Id window_id, mojom::EventPtr event);
   void OnWindowSharedPropertyChanged(Id window_id,
                                      mojo::String name,
@@ -158,7 +160,9 @@
   void OnWindowFocused(Id window_id);
   void OnWindowPredefinedCursorChanged(Id window_id, mojom::Cursor cursor_id);
   void OnChangeCompleted(uint32_t change_id, bool success);
-  void OnTopLevelCreated(uint32_t change_id, mojom::WindowDataPtr window_data);
+  void OnTopLevelCreated(uint32_t change_id,
+                         mojom::WindowDataPtr window_data,
+                         bool drawn);
 
  private:
   void AddChange(const Change& change);
diff --git a/components/mus/ws/test_utils.cc b/components/mus/ws/test_utils.cc
index 673af9f..b94d510 100644
--- a/components/mus/ws/test_utils.cc
+++ b/components/mus/ws/test_utils.cc
@@ -161,9 +161,10 @@
 void TestWindowTreeClient::OnEmbed(uint16_t connection_id,
                                    mojom::WindowDataPtr root,
                                    mus::mojom::WindowTreePtr tree,
-                                   Id focused_window_id) {
+                                   Id focused_window_id,
+                                   bool drawn) {
   // TODO(sky): add test coverage of |focused_window_id|.
-  tracker_.OnEmbed(connection_id, std::move(root));
+  tracker_.OnEmbed(connection_id, std::move(root), drawn);
 }
 
 void TestWindowTreeClient::OnEmbeddedAppDisconnected(uint32_t window) {
@@ -177,8 +178,9 @@
 void TestWindowTreeClient::OnLostCapture(Id window_id) {}
 
 void TestWindowTreeClient::OnTopLevelCreated(uint32_t change_id,
-                                             mojom::WindowDataPtr data) {
-  tracker_.OnTopLevelCreated(change_id, std::move(data));
+                                             mojom::WindowDataPtr data,
+                                             bool drawn) {
+  tracker_.OnTopLevelCreated(change_id, std::move(data), drawn);
 }
 
 void TestWindowTreeClient::OnWindowBoundsChanged(uint32_t window,
@@ -233,9 +235,9 @@
   tracker_.OnWindowVisibilityChanged(window, visible);
 }
 
-void TestWindowTreeClient::OnWindowDrawnStateChanged(uint32_t window,
-                                                     bool drawn) {
-  tracker_.OnWindowDrawnStateChanged(window, drawn);
+void TestWindowTreeClient::OnWindowParentDrawnStateChanged(uint32_t window,
+                                                           bool drawn) {
+  tracker_.OnWindowParentDrawnStateChanged(window, drawn);
 }
 
 void TestWindowTreeClient::OnWindowSharedPropertyChanged(
diff --git a/components/mus/ws/test_utils.h b/components/mus/ws/test_utils.h
index fd6c032..71998d5 100644
--- a/components/mus/ws/test_utils.h
+++ b/components/mus/ws/test_utils.h
@@ -247,12 +247,14 @@
   void OnEmbed(uint16_t connection_id,
                mojom::WindowDataPtr root,
                mus::mojom::WindowTreePtr tree,
-               Id focused_window_id) override;
+               Id focused_window_id,
+               bool drawn) override;
   void OnEmbeddedAppDisconnected(uint32_t window) override;
   void OnUnembed(Id window_id) override;
   void OnLostCapture(Id window_id) override;
   void OnTopLevelCreated(uint32_t change_id,
-                         mojom::WindowDataPtr data) override;
+                         mojom::WindowDataPtr data,
+                         bool drawn) override;
   void OnWindowBoundsChanged(uint32_t window,
                              mojo::RectPtr old_bounds,
                              mojo::RectPtr new_bounds) override;
@@ -278,7 +280,7 @@
                          mojom::OrderDirection direction) override;
   void OnWindowDeleted(uint32_t window) override;
   void OnWindowVisibilityChanged(uint32_t window, bool visible) override;
-  void OnWindowDrawnStateChanged(uint32_t window, bool drawn) override;
+  void OnWindowParentDrawnStateChanged(uint32_t window, bool drawn) override;
   void OnWindowSharedPropertyChanged(uint32_t window,
                                      const mojo::String& name,
                                      mojo::Array<uint8_t> new_data) override;
diff --git a/components/mus/ws/window_tree.cc b/components/mus/ws/window_tree.cc
index b582d85..61a37d0 100644
--- a/components/mus/ws/window_tree.cc
+++ b/components/mus/ws/window_tree.cc
@@ -94,9 +94,10 @@
 
   std::vector<const ServerWindow*> to_send;
   CHECK_EQ(1u, roots_.size());
-  GetUnknownWindowsFrom(*roots_.begin(), &to_send);
+  const ServerWindow* root = *roots_.begin();
+  GetUnknownWindowsFrom(root, &to_send);
 
-  Display* display = GetDisplay(*roots_.begin());
+  Display* display = GetDisplay(root);
   const ServerWindow* focused_window =
       display ? display->GetFocusedWindow() : nullptr;
   if (focused_window)
@@ -105,8 +106,9 @@
   if (focused_window)
     IsWindowKnown(focused_window, &focused_window_id);
 
+  const bool drawn = root->parent() && root->parent()->IsDrawn();
   client()->OnEmbed(id_, WindowToWindowData(to_send.front()), std::move(tree),
-                    focused_window_id.id);
+                    focused_window_id.id, drawn);
 }
 
 void WindowTree::ConfigureWindowManager() {
@@ -340,7 +342,9 @@
   window_id_to_client_id_map_[window->id()] =
       waiting_for_top_level_window_info->client_window_id;
   roots_.insert(window);
-  client()->OnTopLevelCreated(client_change_id, WindowToWindowData(window));
+  const bool drawn = window->parent() && window->parent()->IsDrawn();
+  client()->OnTopLevelCreated(client_change_id, WindowToWindowData(window),
+                              drawn);
 }
 
 void WindowTree::OnChangeCompleted(uint32_t change_id, bool success) {
@@ -817,7 +821,6 @@
   window_data->properties =
       mojo::Map<String, Array<uint8_t>>::From(window->properties());
   window_data->visible = window->visible();
-  window_data->drawn = window->IsDrawn();
   window_data->viewport_metrics =
       window_server_->GetViewportMetricsForWindow(window);
   return window_data;
@@ -850,8 +853,8 @@
 
   for (auto* root : roots_) {
     if (window->Contains(root) && (new_drawn_value != root->IsDrawn())) {
-      client()->OnWindowDrawnStateChanged(ClientWindowIdForWindow(root).id,
-                                          new_drawn_value);
+      client()->OnWindowParentDrawnStateChanged(
+          ClientWindowIdForWindow(root).id, new_drawn_value);
     }
   }
 }
diff --git a/components/mus/ws/window_tree_client_unittest.cc b/components/mus/ws/window_tree_client_unittest.cc
index cd45783..df5c35c5 100644
--- a/components/mus/ws/window_tree_client_unittest.cc
+++ b/components/mus/ws/window_tree_client_unittest.cc
@@ -271,13 +271,14 @@
   void OnEmbed(ConnectionSpecificId connection_id,
                WindowDataPtr root,
                mojom::WindowTreePtr tree,
-               Id focused_window_id) override {
+               Id focused_window_id,
+               bool drawn) override {
     // TODO(sky): add coverage of |focused_window_id|.
     ASSERT_TRUE(root);
     root_window_id_ = root->window_id;
     tree_ = std::move(tree);
     connection_id_ = connection_id;
-    tracker()->OnEmbed(connection_id, std::move(root));
+    tracker()->OnEmbed(connection_id, std::move(root), drawn);
     if (embed_run_loop_)
       embed_run_loop_->Quit();
   }
@@ -289,8 +290,9 @@
     tracker()->OnLostCapture(window_id);
   }
   void OnTopLevelCreated(uint32_t change_id,
-                         mojom::WindowDataPtr data) override {
-    tracker()->OnTopLevelCreated(change_id, std::move(data));
+                         mojom::WindowDataPtr data,
+                         bool drawn) override {
+    tracker()->OnTopLevelCreated(change_id, std::move(data), drawn);
   }
   void OnWindowBoundsChanged(Id window_id,
                              RectPtr old_bounds,
@@ -339,8 +341,8 @@
   void OnWindowVisibilityChanged(uint32_t window, bool visible) override {
     tracker()->OnWindowVisibilityChanged(window, visible);
   }
-  void OnWindowDrawnStateChanged(uint32_t window, bool drawn) override {
-    tracker()->OnWindowDrawnStateChanged(window, drawn);
+  void OnWindowParentDrawnStateChanged(uint32_t window, bool drawn) override {
+    tracker()->OnWindowParentDrawnStateChanged(window, drawn);
   }
   void OnWindowInputEvent(uint32_t event_id,
                           Id window_id,
@@ -1411,12 +1413,12 @@
     std::vector<TestWindow> windows;
     GetWindowTree(wt1(), root_window_id(), &windows);
     ASSERT_EQ(2u, windows.size());
-    EXPECT_EQ(WindowParentToString(root_window_id(), kNullParentId) +
-                  " visible=true drawn=true",
-              windows[0].ToString2());
-    EXPECT_EQ(WindowParentToString(window_1_1, root_window_id()) +
-                  " visible=false drawn=false",
-              windows[1].ToString2());
+    EXPECT_EQ(
+        WindowParentToString(root_window_id(), kNullParentId) + " visible=true",
+        windows[0].ToString2());
+    EXPECT_EQ(
+        WindowParentToString(window_1_1, root_window_id()) + " visible=false",
+        windows[1].ToString2());
   }
 
   // Show all the windows.
@@ -1426,12 +1428,12 @@
     std::vector<TestWindow> windows;
     GetWindowTree(wt1(), root_window_id(), &windows);
     ASSERT_EQ(2u, windows.size());
-    EXPECT_EQ(WindowParentToString(root_window_id(), kNullParentId) +
-                  " visible=true drawn=true",
-              windows[0].ToString2());
-    EXPECT_EQ(WindowParentToString(window_1_1, root_window_id()) +
-                  " visible=true drawn=true",
-              windows[1].ToString2());
+    EXPECT_EQ(
+        WindowParentToString(root_window_id(), kNullParentId) + " visible=true",
+        windows[0].ToString2());
+    EXPECT_EQ(
+        WindowParentToString(window_1_1, root_window_id()) + " visible=true",
+        windows[1].ToString2());
   }
 
   // Hide 1.
@@ -1440,9 +1442,9 @@
     std::vector<TestWindow> windows;
     GetWindowTree(wt1(), window_1_1, &windows);
     ASSERT_EQ(1u, windows.size());
-    EXPECT_EQ(WindowParentToString(window_1_1, root_window_id()) +
-                  " visible=false drawn=false",
-              windows[0].ToString2());
+    EXPECT_EQ(
+        WindowParentToString(window_1_1, root_window_id()) + " visible=false",
+        windows[0].ToString2());
   }
 
   // Attach 2 to 1.
@@ -1451,11 +1453,10 @@
     std::vector<TestWindow> windows;
     GetWindowTree(wt1(), window_1_1, &windows);
     ASSERT_EQ(2u, windows.size());
-    EXPECT_EQ(WindowParentToString(window_1_1, root_window_id()) +
-                  " visible=false drawn=false",
-              windows[0].ToString2());
-    EXPECT_EQ(WindowParentToString(window_1_2, window_1_1) +
-                  " visible=true drawn=false",
+    EXPECT_EQ(
+        WindowParentToString(window_1_1, root_window_id()) + " visible=false",
+        windows[0].ToString2());
+    EXPECT_EQ(WindowParentToString(window_1_2, window_1_1) + " visible=true",
               windows[1].ToString2());
   }
 
@@ -1465,11 +1466,10 @@
     std::vector<TestWindow> windows;
     GetWindowTree(wt1(), window_1_1, &windows);
     ASSERT_EQ(2u, windows.size());
-    EXPECT_EQ(WindowParentToString(window_1_1, root_window_id()) +
-                  " visible=true drawn=true",
-              windows[0].ToString2());
-    EXPECT_EQ(WindowParentToString(window_1_2, window_1_1) +
-                  " visible=true drawn=true",
+    EXPECT_EQ(
+        WindowParentToString(window_1_1, root_window_id()) + " visible=true",
+        windows[0].ToString2());
+    EXPECT_EQ(WindowParentToString(window_1_2, window_1_1) + " visible=true",
               windows[1].ToString2());
   }
 }
@@ -1582,6 +1582,67 @@
   }
 }
 
+// Assertions for SetWindowVisibility sending notifications.
+TEST_F(WindowTreeClientTest, SetWindowVisibilityNotifications2) {
+  // Create 1,1 and 1,2. 1,2 is made a child of 1,1 and 1,1 a child of the root.
+  Id window_1_1 = wt_client1()->NewWindow(1);
+  ASSERT_TRUE(window_1_1);
+  ASSERT_TRUE(wt_client1()->SetWindowVisibility(window_1_1, true));
+  Id window_1_2 = wt_client1()->NewWindow(2);
+  ASSERT_TRUE(window_1_2);
+  ASSERT_TRUE(wt_client1()->AddWindow(root_window_id(), window_1_1));
+  ASSERT_TRUE(wt_client1()->AddWindow(window_1_1, window_1_2));
+
+  // Establish the second connection at 1,2.
+  ASSERT_NO_FATAL_FAILURE(EstablishSecondConnectionWithRoot(window_1_2));
+  EXPECT_EQ("OnEmbed drawn=true", SingleChangeToDescription2(*changes2()));
+  changes2()->clear();
+
+  // Show 1,2 from connection 1. Connection 2 should see this.
+  ASSERT_TRUE(wt_client1()->SetWindowVisibility(window_1_2, true));
+  {
+    wt_client2_->WaitForChangeCount(1);
+    EXPECT_EQ(
+        "VisibilityChanged window=" + IdToString(window_1_2) + " visible=true",
+        SingleChangeToDescription(*changes2()));
+  }
+}
+
+// Assertions for SetWindowVisibility sending notifications.
+TEST_F(WindowTreeClientTest, SetWindowVisibilityNotifications3) {
+  // Create 1,1 and 1,2. 1,2 is made a child of 1,1 and 1,1 a child of the root.
+  Id window_1_1 = wt_client1()->NewWindow(1);
+  ASSERT_TRUE(window_1_1);
+  Id window_1_2 = wt_client1()->NewWindow(2);
+  ASSERT_TRUE(window_1_2);
+  ASSERT_TRUE(wt_client1()->AddWindow(root_window_id(), window_1_1));
+  ASSERT_TRUE(wt_client1()->AddWindow(window_1_1, window_1_2));
+
+  // Establish the second connection at 1,2.
+  ASSERT_NO_FATAL_FAILURE(EstablishSecondConnectionWithRoot(window_1_2));
+  EXPECT_EQ("OnEmbed drawn=false", SingleChangeToDescription2(*changes2()));
+  changes2()->clear();
+
+  // Show 1,1, drawn should be true for 1,2 (as that is all the child sees).
+  ASSERT_TRUE(wt_client1()->SetWindowVisibility(window_1_1, true));
+  {
+    wt_client2_->WaitForChangeCount(1);
+    EXPECT_EQ(
+        "DrawnStateChanged window=" + IdToString(window_1_2) + " drawn=true",
+        SingleChangeToDescription(*changes2()));
+  }
+  changes2()->clear();
+
+  // Show 1,2, visible should be true.
+  ASSERT_TRUE(wt_client1()->SetWindowVisibility(window_1_2, true));
+  {
+    wt_client2_->WaitForChangeCount(1);
+    EXPECT_EQ(
+        "VisibilityChanged window=" + IdToString(window_1_2) + " visible=true",
+        SingleChangeToDescription(*changes2()));
+  }
+}
+
 TEST_F(WindowTreeClientTest, SetWindowProperty) {
   Id window_1_1 = wt_client1()->NewWindow(1);
   ASSERT_TRUE(window_1_1);
diff --git a/components/mus/ws/window_tree_unittest.cc b/components/mus/ws/window_tree_unittest.cc
index 5018616a..509d659 100644
--- a/components/mus/ws/window_tree_unittest.cc
+++ b/components/mus/ws/window_tree_unittest.cc
@@ -526,15 +526,18 @@
   const ClientWindowId embed_window_id2 = BuildClientWindowId(wm_tree(), 2);
   EXPECT_TRUE(
       wm_tree()->NewWindow(embed_window_id2, ServerWindow::Properties()));
+  EXPECT_TRUE(wm_tree()->SetWindowVisibility(embed_window_id2, true));
   EXPECT_TRUE(wm_tree()->AddWindow(FirstRootId(wm_tree()), embed_window_id2));
 
   // Ack the change, which should resume the binding.
+  child_binding->client()->tracker()->changes()->clear();
   static_cast<mojom::WindowManagerClient*>(wm_tree())
       ->OnWmCreatedTopLevelWindow(wm_change_id, embed_window_id2.id);
   EXPECT_FALSE(child_binding->is_paused());
   EXPECT_EQ("TopLevelCreated id=17 window_id=" +
                 WindowIdToString(
-                    WindowIdFromTransportId(embed_window_id2_in_child.id)),
+                    WindowIdFromTransportId(embed_window_id2_in_child.id)) +
+                " drawn=true",
             SingleChangeToDescription(
                 *child_binding->client()->tracker()->changes()));
   child_binding->client()->tracker()->changes()->clear();
@@ -543,21 +546,20 @@
   // client sees the right id.
   ServerWindow* embed_window = wm_tree()->GetWindowByClientId(embed_window_id2);
   ASSERT_TRUE(embed_window);
-  EXPECT_FALSE(embed_window->visible());
-  ASSERT_TRUE(wm_tree()->SetWindowVisibility(
-      ClientWindowIdForWindow(wm_tree(), embed_window), true));
   EXPECT_TRUE(embed_window->visible());
+  ASSERT_TRUE(wm_tree()->SetWindowVisibility(
+      ClientWindowIdForWindow(wm_tree(), embed_window), false));
+  EXPECT_FALSE(embed_window->visible());
   EXPECT_EQ("VisibilityChanged window=" +
                 WindowIdToString(
                     WindowIdFromTransportId(embed_window_id2_in_child.id)) +
-                " visible=true",
+                " visible=false",
             SingleChangeToDescription(
                 *child_binding->client()->tracker()->changes()));
 
   // Set the visibility from the child using the client assigned id.
-  ASSERT_TRUE(
-      child_tree->SetWindowVisibility(embed_window_id2_in_child, false));
-  EXPECT_FALSE(embed_window->visible());
+  ASSERT_TRUE(child_tree->SetWindowVisibility(embed_window_id2_in_child, true));
+  EXPECT_TRUE(embed_window->visible());
 }
 
 // Tests that setting capture only works while an input event is being
diff --git a/components/nacl/browser/nacl_process_host.cc b/components/nacl/browser/nacl_process_host.cc
index 7d604dc..e1a2f275 100644
--- a/components/nacl/browser/nacl_process_host.cc
+++ b/components/nacl/browser/nacl_process_host.cc
@@ -892,35 +892,6 @@
       return false;
     }
 
-#if defined(OS_MACOSX)
-    // For dynamic loading support, NaCl requires a file descriptor that
-    // was created in /tmp, since those created with shm_open() are not
-    // mappable with PROT_EXEC.  Rather than requiring an extra IPC
-    // round trip out of the sandbox, we create an FD here.
-    base::SharedMemory memory_buffer;
-    base::SharedMemoryCreateOptions options;
-    options.size = 1;
-    options.executable = true;
-
-    // NaCl expects a POSIX fd.
-    options.type = base::SharedMemoryHandle::POSIX;
-
-    if (!memory_buffer.Create(options)) {
-      DLOG(ERROR) << "Failed to allocate memory buffer";
-      return false;
-    }
-    base::SharedMemoryHandle duped_handle =
-        base::SharedMemory::DuplicateHandle(memory_buffer.handle());
-    base::ScopedFD memory_fd(
-        base::SharedMemory::GetFdFromSharedMemoryHandle(duped_handle));
-    if (!memory_fd.is_valid()) {
-      DLOG(ERROR) << "Failed to dup() a file descriptor";
-      return false;
-    }
-    params.mac_shm_fd = IPC::GetPlatformFileForTransit(
-        memory_fd.release(), true);
-#endif
-
 #if defined(OS_POSIX)
     if (params.enable_debug_stub) {
       net::SocketDescriptor server_bound_socket = GetDebugStubSocketHandle();
diff --git a/components/nacl/common/nacl_messages.h b/components/nacl/common/nacl_messages.h
index 42188e6..a029d62 100644
--- a/components/nacl/common/nacl_messages.h
+++ b/components/nacl/common/nacl_messages.h
@@ -22,9 +22,6 @@
   IPC_STRUCT_TRAITS_MEMBER(nexe_file)
   IPC_STRUCT_TRAITS_MEMBER(nexe_file_path_metadata)
   IPC_STRUCT_TRAITS_MEMBER(irt_handle)
-#if defined(OS_MACOSX)
-  IPC_STRUCT_TRAITS_MEMBER(mac_shm_fd)
-#endif
 #if defined(OS_POSIX)
   IPC_STRUCT_TRAITS_MEMBER(debug_stub_server_bound_socket)
 #endif
diff --git a/components/nacl/common/nacl_types.cc b/components/nacl/common/nacl_types.cc
index dbb421b..4f6d36f1 100644
--- a/components/nacl/common/nacl_types.cc
+++ b/components/nacl/common/nacl_types.cc
@@ -11,9 +11,6 @@
 NaClStartParams::NaClStartParams()
     : nexe_file(IPC::InvalidPlatformFileForTransit()),
       irt_handle(IPC::InvalidPlatformFileForTransit()),
-#if defined(OS_MACOSX)
-      mac_shm_fd(IPC::InvalidPlatformFileForTransit()),
-#endif
 #if defined(OS_POSIX)
       debug_stub_server_bound_socket(IPC::InvalidPlatformFileForTransit()),
 #endif
diff --git a/components/nacl/common/nacl_types.h b/components/nacl/common/nacl_types.h
index 1d942cd..6c99162 100644
--- a/components/nacl/common/nacl_types.h
+++ b/components/nacl/common/nacl_types.h
@@ -75,9 +75,6 @@
   base::FilePath nexe_file_path_metadata;
 
   IPC::PlatformFileForTransit irt_handle;
-#if defined(OS_MACOSX)
-  IPC::PlatformFileForTransit mac_shm_fd;
-#endif
 #if defined(OS_POSIX)
   IPC::PlatformFileForTransit debug_stub_server_bound_socket;
 #endif
diff --git a/components/nacl/loader/nacl_listener.cc b/components/nacl/loader/nacl_listener.cc
index 01c8c24..4dfb680 100644
--- a/components/nacl/loader/nacl_listener.cc
+++ b/components/nacl/loader/nacl_listener.cc
@@ -73,39 +73,7 @@
           static_cast<NaClErrorCode>(load_status)));
 }
 
-#if defined(OS_MACOSX)
-
-// On Mac OS X, shm_open() works in the sandbox but does not give us
-// an FD that we can map as PROT_EXEC.  Rather than doing an IPC to
-// get an executable SHM region when CreateMemoryObject() is called,
-// we preallocate one on startup, since NaCl's sel_ldr only needs one
-// of them.  This saves a round trip.
-
-base::subtle::Atomic32 g_shm_fd = -1;
-
-int CreateMemoryObject(size_t size, int executable) {
-  if (executable && size > 0) {
-    int result_fd = base::subtle::NoBarrier_AtomicExchange(&g_shm_fd, -1);
-    if (result_fd != -1) {
-      // ftruncate() is disallowed by the Mac OS X sandbox and
-      // returns EPERM.  Luckily, we can get the same effect with
-      // lseek() + write().
-      if (lseek(result_fd, size - 1, SEEK_SET) == -1) {
-        LOG(ERROR) << "lseek() failed: " << errno;
-        return -1;
-      }
-      if (write(result_fd, "", 1) != 1) {
-        LOG(ERROR) << "write() failed: " << errno;
-        return -1;
-      }
-      return result_fd;
-    }
-  }
-  // Fall back to NaCl's default implementation.
-  return -1;
-}
-
-#elif defined(OS_LINUX)
+#if defined(OS_LINUX)
 
 int CreateMemoryObject(size_t size, int executable) {
   return content::MakeSharedMemorySegmentViaIPC(size, executable);
@@ -379,13 +347,12 @@
     LOG(FATAL) << "NaClChromeMainArgsCreate() failed";
   }
 
-#if defined(OS_LINUX) || defined(OS_MACOSX)
+#if defined(OS_POSIX)
   args->number_of_cores = number_of_cores_;
+#endif
+
+#if defined(OS_LINUX)
   args->create_memory_object_func = CreateMemoryObject;
-# if defined(OS_MACOSX)
-  CHECK(params.mac_shm_fd != IPC::InvalidPlatformFileForTransit());
-  g_shm_fd = IPC::PlatformFileForTransitToPlatformFile(params.mac_shm_fd);
-# endif
 #endif
 
   DCHECK(params.process_type != nacl::kUnknownNaClProcessType);
diff --git a/content/browser/accessibility/browser_accessibility.cc b/content/browser/accessibility/browser_accessibility.cc
index 9e93be4..fa606fc 100644
--- a/content/browser/accessibility/browser_accessibility.cc
+++ b/content/browser/accessibility/browser_accessibility.cc
@@ -96,7 +96,7 @@
     BrowserAccessibilityManager* child_manager =
         BrowserAccessibilityManager::FromID(
             GetIntAttribute(ui::AX_ATTR_CHILD_TREE_ID));
-    if (child_manager)
+    if (child_manager && child_manager->GetRoot()->GetParent() == this)
       return 1;
 
     return 0;
@@ -138,7 +138,7 @@
     BrowserAccessibilityManager* child_manager =
         BrowserAccessibilityManager::FromID(
             GetIntAttribute(ui::AX_ATTR_CHILD_TREE_ID));
-    if (child_manager)
+    if (child_manager && child_manager->GetRoot()->GetParent() == this)
       result = child_manager->GetRoot();
   } else {
     result = InternalGetChild(child_index);
diff --git a/content/browser/accessibility/browser_accessibility_win.cc b/content/browser/accessibility/browser_accessibility_win.cc
index d68475f8..48bc352 100644
--- a/content/browser/accessibility/browser_accessibility_win.cc
+++ b/content/browser/accessibility/browser_accessibility_win.cc
@@ -4582,8 +4582,15 @@
       ia_state |= STATE_SYSTEM_FOCUSABLE;
       break;
     case ui::AX_ROLE_EMBEDDED_OBJECT:
-      ia_role = ROLE_SYSTEM_CLIENT;
-      ia2_role = IA2_ROLE_EMBEDDED_OBJECT;
+      if (HasIntAttribute(ui::AX_ATTR_CHILD_TREE_ID)) {
+        // Windows screen readers assume that IA2_ROLE_EMBEDDED_OBJECT
+        // doesn't have any children, but it may be something like a
+        // browser plugin that has a document inside.
+        ia_role = ROLE_SYSTEM_GROUPING;
+      } else {
+        ia_role = ROLE_SYSTEM_CLIENT;
+        ia2_role = IA2_ROLE_EMBEDDED_OBJECT;
+      }
       break;
     case ui::AX_ROLE_FIGCAPTION:
       role_name = html_tag;
diff --git a/content/browser/android/browser_jni_registrar.cc b/content/browser/android/browser_jni_registrar.cc
index 1be2ea5..87d8d592 100644
--- a/content/browser/android/browser_jni_registrar.cc
+++ b/content/browser/android/browser_jni_registrar.cc
@@ -22,6 +22,7 @@
 #include "content/browser/android/interstitial_page_delegate_android.h"
 #include "content/browser/android/load_url_params.h"
 #include "content/browser/android/popup_touch_handle_drawable.h"
+#include "content/browser/android/service_registry_android_impl.h"
 #include "content/browser/android/tracing_controller_android.h"
 #include "content/browser/android/web_contents_observer_proxy.h"
 #include "content/browser/device_sensors/sensor_manager_android.h"
@@ -31,7 +32,6 @@
 #include "content/browser/media/android/media_resource_getter_impl.h"
 #include "content/browser/media/session/media_session_delegate_android.h"
 #include "content/browser/mojo/service_registrar_android.h"
-#include "content/browser/mojo/service_registry_android.h"
 #include "content/browser/power_save_blocker_android.h"
 #include "content/browser/renderer_host/ime_adapter_android.h"
 #include "content/browser/renderer_host/input/synthetic_gesture_target_android.h"
@@ -89,7 +89,7 @@
      content::ScreenOrientationDelegateAndroid::Register},
     {"SensorManagerAndroid", content::SensorManagerAndroid::Register},
     {"ServiceRegistrarAndroid", content::ServiceRegistrarAndroid::Register},
-    {"ServiceRegistryAndroid", content::ServiceRegistryAndroid::Register},
+    {"ServiceRegistryAndroid", content::ServiceRegistryAndroidImpl::Register},
     {"SpeechRecognizerImplAndroid",
      content::SpeechRecognizerImplAndroid::RegisterSpeechRecognizer},
     {"TimeZoneMonitorAndroid", content::TimeZoneMonitorAndroid::Register},
diff --git a/content/browser/mojo/service_registry_android.cc b/content/browser/android/service_registry_android_impl.cc
similarity index 65%
rename from content/browser/mojo/service_registry_android.cc
rename to content/browser/android/service_registry_android_impl.cc
index 0e80e08..e54c3610 100644
--- a/content/browser/mojo/service_registry_android.cc
+++ b/content/browser/android/service_registry_android_impl.cc
@@ -1,16 +1,18 @@
-// Copyright 2014 The Chromium Authors. All rights reserved.
+// Copyright 2016 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 "content/browser/mojo/service_registry_android.h"
+#include "content/browser/android/service_registry_android_impl.h"
 
 #include <utility>
 
 #include "base/android/jni_android.h"
 #include "base/android/jni_string.h"
 #include "base/callback.h"
-#include "content/common/mojo/service_registry_impl.h"
+#include "base/memory/ptr_util.h"
+#include "content/public/common/service_registry.h"
 #include "jni/ServiceRegistry_jni.h"
+#include "mojo/public/cpp/system/message_pipe.h"
 
 using base::android::AttachCurrentThread;
 using base::android::ConvertJavaStringToUTF8;
@@ -28,23 +30,31 @@
     const ScopedJavaGlobalRef<jobject>& j_scoped_factory,
     mojo::ScopedMessagePipeHandle handle) {
   JNIEnv* env = AttachCurrentThread();
-  Java_ServiceRegistry_createImplAndAttach(env,
-                                           j_scoped_service_registry.obj(),
-                                           handle.release().value(),
-                                           j_scoped_manager.obj(),
-                                           j_scoped_factory.obj());
+  Java_ServiceRegistry_createImplAndAttach(
+      env, j_scoped_service_registry.obj(), handle.release().value(),
+      j_scoped_manager.obj(), j_scoped_factory.obj());
 }
 
 }  // namespace
 
 // static
-bool ServiceRegistryAndroid::Register(JNIEnv* env) {
+std::unique_ptr<ServiceRegistryAndroid> ServiceRegistryAndroid::Create(
+    ServiceRegistry* registry) {
+  return base::WrapUnique(new ServiceRegistryAndroidImpl(registry));
+}
+
+// static
+bool ServiceRegistryAndroidImpl::Register(JNIEnv* env) {
   return RegisterNativesImpl(env);
 }
 
+ServiceRegistryAndroidImpl::~ServiceRegistryAndroidImpl() {
+  Java_ServiceRegistry_destroy(AttachCurrentThread(), obj_.obj());
+}
+
 // Constructor and destructor call into Java.
-ServiceRegistryAndroid::ServiceRegistryAndroid(
-    ServiceRegistryImpl* service_registry)
+ServiceRegistryAndroidImpl::ServiceRegistryAndroidImpl(
+    ServiceRegistry* service_registry)
     : service_registry_(service_registry) {
   JNIEnv* env = AttachCurrentThread();
   obj_.Reset(
@@ -52,12 +62,13 @@
       Java_ServiceRegistry_create(env, reinterpret_cast<intptr_t>(this)).obj());
 }
 
-ServiceRegistryAndroid::~ServiceRegistryAndroid() {
-  Java_ServiceRegistry_destroy(AttachCurrentThread(), obj_.obj());
+const base::android::ScopedJavaGlobalRef<jobject>&
+ServiceRegistryAndroidImpl::GetObj() {
+  return obj_;
 }
 
 // Methods called from Java.
-void ServiceRegistryAndroid::AddService(
+void ServiceRegistryAndroidImpl::AddService(
     JNIEnv* env,
     const JavaParamRef<jobject>& j_service_registry,
     const JavaParamRef<jobject>& j_manager,
@@ -74,14 +85,12 @@
   ScopedJavaGlobalRef<jobject> j_scoped_factory;
   j_scoped_factory.Reset(env, j_factory);
 
-  service_registry_->AddService(name,
-                                base::Bind(&CreateImplAndAttach,
-                                           j_scoped_service_registry,
-                                           j_scoped_manager,
-                                           j_scoped_factory));
+  service_registry_->AddService(
+      name, base::Bind(&CreateImplAndAttach, j_scoped_service_registry,
+                       j_scoped_manager, j_scoped_factory));
 }
 
-void ServiceRegistryAndroid::RemoveService(
+void ServiceRegistryAndroidImpl::RemoveService(
     JNIEnv* env,
     const JavaParamRef<jobject>& j_service_registry,
     const JavaParamRef<jstring>& j_name) {
@@ -89,7 +98,7 @@
   service_registry_->RemoveService(name);
 }
 
-void ServiceRegistryAndroid::ConnectToRemoteService(
+void ServiceRegistryAndroidImpl::ConnectToRemoteService(
     JNIEnv* env,
     const JavaParamRef<jobject>& j_service_registry,
     const JavaParamRef<jstring>& j_name,
diff --git a/content/browser/android/service_registry_android_impl.h b/content/browser/android/service_registry_android_impl.h
new file mode 100644
index 0000000..2620313c8
--- /dev/null
+++ b/content/browser/android/service_registry_android_impl.h
@@ -0,0 +1,53 @@
+// Copyright 2016 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 CONTENT_BROWSER_ANDROID_SERVICE_REGISTRY_ANDROID_IMPL_H_
+#define CONTENT_BROWSER_ANDROID_SERVICE_REGISTRY_ANDROID_IMPL_H_
+
+#include <jni.h>
+
+#include "base/macros.h"
+#include "content/public/browser/android/service_registry_android.h"
+
+namespace content {
+
+class ServiceRegistryAndroidImpl : public ServiceRegistryAndroid {
+ public:
+  static bool Register(JNIEnv* env);
+
+  ~ServiceRegistryAndroidImpl() override;
+
+ private:
+  friend class ServiceRegistryAndroid;
+
+  // Use ServiceRegistryAndroid::Create() to create an instance.
+  explicit ServiceRegistryAndroidImpl(ServiceRegistry* service_registry);
+
+  // ServiceRegistryAndroid implementation:
+  void AddService(
+      JNIEnv* env,
+      const base::android::JavaParamRef<jobject>& j_service_registry,
+      const base::android::JavaParamRef<jobject>& j_manager,
+      const base::android::JavaParamRef<jobject>& j_factory,
+      const base::android::JavaParamRef<jstring>& j_name) override;
+  void RemoveService(
+      JNIEnv* env,
+      const base::android::JavaParamRef<jobject>& j_service_registry,
+      const base::android::JavaParamRef<jstring>& j_name) override;
+  void ConnectToRemoteService(
+      JNIEnv* env,
+      const base::android::JavaParamRef<jobject>& j_service_registry,
+      const base::android::JavaParamRef<jstring>& j_name,
+      jint handle) override;
+  const base::android::ScopedJavaGlobalRef<jobject>& GetObj() override;
+
+  ServiceRegistry* service_registry_;
+  base::android::ScopedJavaGlobalRef<jobject> obj_;
+
+  DISALLOW_COPY_AND_ASSIGN(ServiceRegistryAndroidImpl);
+};
+
+}  // namespace content
+
+#endif  // CONTENT_BROWSER_ANDROID_SERVICE_REGISTRY_ANDROID_IMPL_H_
diff --git a/content/browser/appcache/appcache_response.cc b/content/browser/appcache/appcache_response.cc
index 20a8b8a3..b5df22d 100644
--- a/content/browser/appcache/appcache_response.cc
+++ b/content/browser/appcache/appcache_response.cc
@@ -78,11 +78,24 @@
 
 HttpResponseInfoIOBuffer::~HttpResponseInfoIOBuffer() {}
 
+// AppCacheDiskCacheInterface ----------------------------------------
+
+AppCacheDiskCacheInterface::AppCacheDiskCacheInterface()
+    : weak_factory_(this) {}
+
+base::WeakPtr<AppCacheDiskCacheInterface>
+AppCacheDiskCacheInterface::GetWeakPtr() {
+  return weak_factory_.GetWeakPtr();
+}
+
+AppCacheDiskCacheInterface::~AppCacheDiskCacheInterface() {}
+
 // AppCacheResponseIO ----------------------------------------------
 
-AppCacheResponseIO::AppCacheResponseIO(int64_t response_id,
-                                       int64_t group_id,
-                                       AppCacheDiskCacheInterface* disk_cache)
+AppCacheResponseIO::AppCacheResponseIO(
+    int64_t response_id,
+    int64_t group_id,
+    const base::WeakPtr<AppCacheDiskCacheInterface>& disk_cache)
     : response_id_(response_id),
       group_id_(group_id),
       disk_cache_(disk_cache),
@@ -177,7 +190,7 @@
 AppCacheResponseReader::AppCacheResponseReader(
     int64_t response_id,
     int64_t group_id,
-    AppCacheDiskCacheInterface* disk_cache)
+    const base::WeakPtr<AppCacheDiskCacheInterface>& disk_cache)
     : AppCacheResponseIO(response_id, group_id, disk_cache),
       range_offset_(0),
       range_length_(std::numeric_limits<int32_t>::max()),
@@ -302,7 +315,7 @@
 AppCacheResponseWriter::AppCacheResponseWriter(
     int64_t response_id,
     int64_t group_id,
-    AppCacheDiskCacheInterface* disk_cache)
+    const base::WeakPtr<AppCacheDiskCacheInterface>& disk_cache)
     : AppCacheResponseIO(response_id, group_id, disk_cache),
       info_size_(0),
       write_position_(0),
@@ -404,7 +417,10 @@
     AppCacheDiskCacheInterface::Entry** entry, int rv) {
   DCHECK(info_buffer_.get() || buffer_.get());
 
-  if (creation_phase_ == INITIAL_ATTEMPT) {
+  if (!disk_cache_) {
+    ScheduleIOCompletionCallback(net::ERR_FAILED);
+    return;
+  } else if (creation_phase_ == INITIAL_ATTEMPT) {
     if (rv != net::OK) {
       // We may try to overwrite existing entries.
       creation_phase_ = DOOM_EXISTING;
@@ -444,7 +460,7 @@
 AppCacheResponseMetadataWriter::AppCacheResponseMetadataWriter(
     int64_t response_id,
     int64_t group_id,
-    AppCacheDiskCacheInterface* disk_cache)
+    const base::WeakPtr<AppCacheDiskCacheInterface>& disk_cache)
     : AppCacheResponseIO(response_id, group_id, disk_cache),
       write_amount_(0),
       weak_factory_(this) {}
diff --git a/content/browser/appcache/appcache_response.h b/content/browser/appcache/appcache_response.h
index 8543b2b9..0b709b9 100644
--- a/content/browser/appcache/appcache_response.h
+++ b/content/browser/appcache/appcache_response.h
@@ -93,6 +93,8 @@
     virtual ~Entry() {}
   };
 
+  AppCacheDiskCacheInterface();
+
   virtual int CreateEntry(int64_t key,
                           Entry** entry,
                           const net::CompletionCallback& callback) = 0;
@@ -102,9 +104,12 @@
   virtual int DoomEntry(int64_t key,
                         const net::CompletionCallback& callback) = 0;
 
+  base::WeakPtr<AppCacheDiskCacheInterface> GetWeakPtr();
+
  protected:
-  friend class base::RefCounted<AppCacheDiskCacheInterface>;
-  virtual ~AppCacheDiskCacheInterface() {}
+  virtual ~AppCacheDiskCacheInterface();
+
+  base::WeakPtrFactory<AppCacheDiskCacheInterface> weak_factory_;
 };
 
 // Common base class for response reader and writer.
@@ -114,9 +119,10 @@
   int64_t response_id() const { return response_id_; }
 
  protected:
-  AppCacheResponseIO(int64_t response_id,
-                     int64_t group_id,
-                     AppCacheDiskCacheInterface* disk_cache);
+  AppCacheResponseIO(
+      int64_t response_id,
+      int64_t group_id,
+      const base::WeakPtr<AppCacheDiskCacheInterface>& disk_cache);
 
   virtual void OnIOComplete(int result) = 0;
   virtual void OnOpenEntryComplete() {}
@@ -130,7 +136,7 @@
 
   const int64_t response_id_;
   const int64_t group_id_;
-  AppCacheDiskCacheInterface* disk_cache_;
+  base::WeakPtr<AppCacheDiskCacheInterface> disk_cache_;
   AppCacheDiskCacheInterface::Entry* entry_;
   scoped_refptr<HttpResponseInfoIOBuffer> info_buffer_;
   scoped_refptr<net::IOBuffer> buffer_;
@@ -190,9 +196,10 @@
   friend class content::MockAppCacheStorage;
 
   // Should only be constructed by the storage class and derivatives.
-  AppCacheResponseReader(int64_t response_id,
-                         int64_t group_id,
-                         AppCacheDiskCacheInterface* disk_cache);
+  AppCacheResponseReader(
+      int64_t response_id,
+      int64_t group_id,
+      const base::WeakPtr<AppCacheDiskCacheInterface>& disk_cache);
 
   void OnIOComplete(int result) override;
   void OnOpenEntryComplete() override;
@@ -247,9 +254,10 @@
 
  protected:
   // Should only be constructed by the storage class and derivatives.
-  AppCacheResponseWriter(int64_t response_id,
-                         int64_t group_id,
-                         AppCacheDiskCacheInterface* disk_cache);
+  AppCacheResponseWriter(
+      int64_t response_id,
+      int64_t group_id,
+      const base::WeakPtr<AppCacheDiskCacheInterface>& disk_cache);
 
  private:
   friend class AppCacheStorageImpl;
@@ -304,10 +312,12 @@
  protected:
   friend class AppCacheStorageImpl;
   friend class content::MockAppCacheStorage;
+
   // Should only be constructed by the storage class and derivatives.
-  AppCacheResponseMetadataWriter(int64_t response_id,
-                                 int64_t group_id,
-                                 AppCacheDiskCacheInterface* disk_cache);
+  AppCacheResponseMetadataWriter(
+      int64_t response_id,
+      int64_t group_id,
+      const base::WeakPtr<AppCacheDiskCacheInterface>& disk_cache);
 
  private:
   void OnIOComplete(int result) override;
diff --git a/content/browser/appcache/appcache_service_unittest.cc b/content/browser/appcache/appcache_service_unittest.cc
index 79febf76..5c29d50 100644
--- a/content/browser/appcache/appcache_service_unittest.cc
+++ b/content/browser/appcache/appcache_service_unittest.cc
@@ -42,7 +42,9 @@
                      int info_size,
                      const char* data,
                      int data_size)
-      : AppCacheResponseReader(response_id, 0, NULL),
+      : AppCacheResponseReader(response_id,
+                               0,
+                               base::WeakPtr<AppCacheDiskCacheInterface>()),
         info_(info),
         info_size_(info_size),
         data_(data),
diff --git a/content/browser/appcache/appcache_storage_impl.cc b/content/browser/appcache/appcache_storage_impl.cc
index fbb72905..ceb52271 100644
--- a/content/browser/appcache/appcache_storage_impl.cc
+++ b/content/browser/appcache/appcache_storage_impl.cc
@@ -1736,20 +1736,22 @@
     const GURL& manifest_url,
     int64_t group_id,
     int64_t response_id) {
-  return new AppCacheResponseReader(response_id, group_id, disk_cache());
+  return new AppCacheResponseReader(response_id, group_id,
+                                    disk_cache()->GetWeakPtr());
 }
 
 AppCacheResponseWriter* AppCacheStorageImpl::CreateResponseWriter(
     const GURL& manifest_url,
     int64_t group_id) {
-  return new AppCacheResponseWriter(NewResponseId(), group_id, disk_cache());
+  return new AppCacheResponseWriter(NewResponseId(), group_id,
+                                    disk_cache()->GetWeakPtr());
 }
 
 AppCacheResponseMetadataWriter*
 AppCacheStorageImpl::CreateResponseMetadataWriter(int64_t group_id,
                                                   int64_t response_id) {
   return new AppCacheResponseMetadataWriter(response_id, group_id,
-                                            disk_cache());
+                                            disk_cache()->GetWeakPtr());
 }
 
 void AppCacheStorageImpl::DoomResponses(
diff --git a/content/browser/appcache/mock_appcache_storage.cc b/content/browser/appcache/mock_appcache_storage.cc
index 09bdf03..5d7cd8d 100644
--- a/content/browser/appcache/mock_appcache_storage.cc
+++ b/content/browser/appcache/mock_appcache_storage.cc
@@ -169,20 +169,22 @@
     int64_t response_id) {
   if (simulated_reader_)
     return simulated_reader_.release();
-  return new AppCacheResponseReader(response_id, group_id, disk_cache());
+  return new AppCacheResponseReader(response_id, group_id,
+                                    disk_cache()->GetWeakPtr());
 }
 
 AppCacheResponseWriter* MockAppCacheStorage::CreateResponseWriter(
     const GURL& manifest_url,
     int64_t group_id) {
-  return new AppCacheResponseWriter(NewResponseId(),  group_id, disk_cache());
+  return new AppCacheResponseWriter(NewResponseId(), group_id,
+                                    disk_cache()->GetWeakPtr());
 }
 
 AppCacheResponseMetadataWriter*
 MockAppCacheStorage::CreateResponseMetadataWriter(int64_t group_id,
                                                   int64_t response_id) {
   return new AppCacheResponseMetadataWriter(response_id, group_id,
-                                            disk_cache());
+                                            disk_cache()->GetWeakPtr());
 }
 
 void MockAppCacheStorage::DoomResponses(
diff --git a/content/browser/bluetooth/bluetooth_blacklist.cc b/content/browser/bluetooth/bluetooth_blacklist.cc
index 088848f..086861eb 100644
--- a/content/browser/bluetooth/bluetooth_blacklist.cc
+++ b/content/browser/bluetooth/bluetooth_blacklist.cc
@@ -8,6 +8,7 @@
 #include "base/metrics/histogram_macros.h"
 #include "base/strings/string_split.h"
 #include "content/common/bluetooth/bluetooth_scan_filter.h"
+#include "content/public/browser/content_browser_client.h"
 
 using device::BluetoothUUID;
 
@@ -127,10 +128,12 @@
 void BluetoothBlacklist::ResetToDefaultValuesForTest() {
   blacklisted_uuids_.clear();
   PopulateWithDefaultValues();
+  PopulateWithServerProvidedValues();
 }
 
 BluetoothBlacklist::BluetoothBlacklist() {
   PopulateWithDefaultValues();
+  PopulateWithServerProvidedValues();
 }
 
 void BluetoothBlacklist::PopulateWithDefaultValues() {
@@ -172,4 +175,8 @@
       Value::EXCLUDE_READS);
 }
 
+void BluetoothBlacklist::PopulateWithServerProvidedValues() {
+  Add(GetContentClient()->browser()->GetWebBluetoothBlacklist());
+}
+
 }  // namespace content
diff --git a/content/browser/bluetooth/bluetooth_blacklist.h b/content/browser/bluetooth/bluetooth_blacklist.h
index b58330bf..d363d86 100644
--- a/content/browser/bluetooth/bluetooth_blacklist.h
+++ b/content/browser/bluetooth/bluetooth_blacklist.h
@@ -53,19 +53,11 @@
   // Adds UUIDs to the blacklist by parsing a blacklist string and calling
   // Add(uuid, value).
   //
-  // The blacklist string must be a comma-separated list of UUID:exclusion
-  // pairs. The pairs may be separated by whitespace. Pair components are
-  // colon-separated and must not have whitespace around the colon.
-  //
-  // UUIDs are a string that BluetoothUUID can parse (See BluetoothUUID
-  // constructor comment). Exclusion values are a single lower case character
-  // string "e", "r", or "w" for EXCLUDE, EXCLUDE_READS, or EXCLUDE_WRITES.
+  // The blacklist string format is defined at
+  // ContentBrowserClient::GetWebBluetoothBlacklist().
   //
   // Malformed pairs in the string are ignored, including invalid UUID or
   // exclusion values. Duplicate UUIDs follow Add()'s merging rule.
-  //
-  // Example:
-  // "1812:e, 00001800-0000-1000-8000-00805f9b34fb:w, ignored:1, alsoignored."
   void Add(base::StringPiece blacklist_string);
 
   // Returns if a UUID is excluded from all operations. UUID must be valid.
@@ -97,6 +89,10 @@
 
   void PopulateWithDefaultValues();
 
+  // Populates blacklist with values obtained dynamically from a server, able
+  // to be updated without shipping new executable versions.
+  void PopulateWithServerProvidedValues();
+
   // Map of UUID to blacklisted value.
   std::map<device::BluetoothUUID, Value> blacklisted_uuids_;
 
diff --git a/content/browser/bluetooth/bluetooth_dispatcher_host.cc b/content/browser/bluetooth/bluetooth_dispatcher_host.cc
index c7a2dd3..23718c9 100644
--- a/content/browser/bluetooth/bluetooth_dispatcher_host.cc
+++ b/content/browser/bluetooth/bluetooth_dispatcher_host.cc
@@ -1137,13 +1137,18 @@
   const url::Origin embedding_origin =
       web_contents->GetMainFrame()->GetLastCommittedOrigin();
 
-  if (requesting_origin.unique()) {
-    VLOG(1) << "Request device with unique origin.";
+  // TODO(crbug.com/518042): Enforce correctly-delegated permissions instead of
+  // matching origins. When relaxing this, take care to handle non-sandboxed
+  // unique origins.
+  if (!embedding_origin.IsSameOriginWith(requesting_origin)) {
     Send(new BluetoothMsg_RequestDeviceError(
         thread_id, request_id,
-        WebBluetoothError::REQUEST_DEVICE_WITH_UNIQUE_ORIGIN));
+        WebBluetoothError::REQUEST_DEVICE_FROM_CROSS_ORIGIN_IFRAME));
     return;
   }
+  // The above also excludes unique origins, which are not even same-origin with
+  // themselves.
+  DCHECK(!requesting_origin.unique());
 
   DCHECK(adapter_.get());
 
diff --git a/content/browser/browsing_instance.h b/content/browser/browsing_instance.h
index 4beb487b..34c1f073 100644
--- a/content/browser/browsing_instance.h
+++ b/content/browser/browsing_instance.h
@@ -8,6 +8,7 @@
 #include <stddef.h>
 
 #include "base/containers/hash_tables.h"
+#include "base/gtest_prod_util.h"
 #include "base/lazy_instance.h"
 #include "base/logging.h"
 #include "base/macros.h"
@@ -54,12 +55,20 @@
 // site_instance_unittest.cc.
 //
 ///////////////////////////////////////////////////////////////////////////////
-class CONTENT_EXPORT BrowsingInstance
+class CONTENT_EXPORT BrowsingInstance final
     : public base::RefCounted<BrowsingInstance> {
- protected:
+ private:
+  friend class base::RefCounted<BrowsingInstance>;
+  friend class SiteInstanceImpl;
+  FRIEND_TEST_ALL_PREFIXES(SiteInstanceTest, OneSiteInstancePerSite);
+  FRIEND_TEST_ALL_PREFIXES(SiteInstanceTest,
+                           OneSiteInstancePerSiteInBrowserContext);
+
   // Create a new BrowsingInstance.
   explicit BrowsingInstance(BrowserContext* context);
 
+  ~BrowsingInstance();
+
   // Get the browser context to which this BrowsingInstance belongs.
   BrowserContext* browser_context() const { return browser_context_; }
 
@@ -96,14 +105,6 @@
     active_contents_count_--;
   }
 
-  friend class SiteInstanceImpl;
-
-  friend class base::RefCounted<BrowsingInstance>;
-
-  // Virtual to allow tests to extend it.
-  virtual ~BrowsingInstance();
-
- private:
   // Map of site to SiteInstance, to ensure we only have one SiteInstance per
   // site.
   typedef base::hash_map<std::string, SiteInstanceImpl*> SiteInstanceMap;
diff --git a/content/browser/compositor/buffer_queue.cc b/content/browser/compositor/buffer_queue.cc
index bb1919e..cafb6d96 100644
--- a/content/browser/compositor/buffer_queue.cc
+++ b/content/browser/compositor/buffer_queue.cc
@@ -8,10 +8,10 @@
 #include "build/build_config.h"
 #include "content/browser/compositor/gl_helper.h"
 #include "content/browser/compositor/image_transport_factory.h"
-#include "content/browser/gpu/browser_gpu_memory_buffer_manager.h"
 #include "content/common/gpu/client/context_provider_command_buffer.h"
 #include "gpu/GLES2/gl2extchromium.h"
 #include "gpu/command_buffer/client/gles2_interface.h"
+#include "gpu/command_buffer/client/gpu_memory_buffer_manager.h"
 #include "gpu/command_buffer/common/gpu_memory_buffer_support.h"
 #include "gpu/command_buffer/service/image_factory.h"
 #include "third_party/skia/include/core/SkRect.h"
@@ -21,13 +21,12 @@
 
 namespace content {
 
-BufferQueue::BufferQueue(
-    scoped_refptr<cc::ContextProvider> context_provider,
-    unsigned int texture_target,
-    unsigned int internalformat,
-    GLHelper* gl_helper,
-    BrowserGpuMemoryBufferManager* gpu_memory_buffer_manager,
-    int surface_id)
+BufferQueue::BufferQueue(scoped_refptr<cc::ContextProvider> context_provider,
+                         unsigned int texture_target,
+                         unsigned int internalformat,
+                         GLHelper* gl_helper,
+                         gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
+                         int surface_id)
     : context_provider_(context_provider),
       fbo_(0),
       allocated_count_(0),
@@ -223,9 +222,9 @@
   DCHECK_LT(allocated_count_, 4U);
 
   scoped_ptr<gfx::GpuMemoryBuffer> buffer(
-      gpu_memory_buffer_manager_->AllocateGpuMemoryBufferForScanout(
+      gpu_memory_buffer_manager_->AllocateGpuMemoryBuffer(
           size_, gpu::DefaultBufferFormatForImageFormat(internal_format_),
-          surface_id_));
+          gfx::BufferUsage::SCANOUT, surface_id_));
   if (!buffer.get()) {
     gl->DeleteTextures(1, &texture);
     DLOG(ERROR) << "Failed to allocate GPU memory buffer";
diff --git a/content/browser/compositor/buffer_queue.h b/content/browser/compositor/buffer_queue.h
index 4c7d9439..47b4a7dd 100644
--- a/content/browser/compositor/buffer_queue.h
+++ b/content/browser/compositor/buffer_queue.h
@@ -25,9 +25,12 @@
 class GpuMemoryBuffer;
 }
 
+namespace gpu {
+class GpuMemoryBufferManager;
+}
+
 namespace content {
 
-class BrowserGpuMemoryBufferManager;
 class GLHelper;
 
 // Provides a surface that manages its own buffers, backed by GpuMemoryBuffers
@@ -40,7 +43,7 @@
               unsigned int texture_target,
               unsigned int internalformat,
               GLHelper* gl_helper,
-              BrowserGpuMemoryBufferManager* gpu_memory_buffer_manager,
+              gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
               int surface_id);
   virtual ~BufferQueue();
 
@@ -112,7 +115,7 @@
   // may be nullptr, if they represent frames that have been destroyed.
   std::deque<scoped_ptr<AllocatedSurface>> in_flight_surfaces_;
   GLHelper* gl_helper_;
-  BrowserGpuMemoryBufferManager* gpu_memory_buffer_manager_;
+  gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager_;
   int surface_id_;
 
   DISALLOW_COPY_AND_ASSIGN(BufferQueue);
diff --git a/content/browser/compositor/buffer_queue_unittest.cc b/content/browser/compositor/buffer_queue_unittest.cc
index 0a93a7e..6e1dc9f 100644
--- a/content/browser/compositor/buffer_queue_unittest.cc
+++ b/content/browser/compositor/buffer_queue_unittest.cc
@@ -57,10 +57,15 @@
 
   void set_allocate_succeeds(bool value) { allocate_succeeds_ = value; }
 
-  scoped_ptr<gfx::GpuMemoryBuffer> AllocateGpuMemoryBufferForScanout(
+  scoped_ptr<gfx::GpuMemoryBuffer> AllocateGpuMemoryBuffer(
       const gfx::Size& size,
       gfx::BufferFormat format,
+      gfx::BufferUsage usage,
       int32_t surface_id) override {
+    if (!surface_id) {
+      return BrowserGpuMemoryBufferManager::AllocateGpuMemoryBuffer(
+          size, format, usage, surface_id);
+    }
     if (allocate_succeeds_)
       return make_scoped_ptr<gfx::GpuMemoryBuffer>(new StubGpuMemoryBufferImpl);
     return nullptr;
diff --git a/content/browser/compositor/gpu_surfaceless_browser_compositor_output_surface.cc b/content/browser/compositor/gpu_surfaceless_browser_compositor_output_surface.cc
index d038fa86..5e85a4e3 100644
--- a/content/browser/compositor/gpu_surfaceless_browser_compositor_output_surface.cc
+++ b/content/browser/compositor/gpu_surfaceless_browser_compositor_output_surface.cc
@@ -29,7 +29,7 @@
             overlay_candidate_validator,
         unsigned int target,
         unsigned int internalformat,
-        BrowserGpuMemoryBufferManager* gpu_memory_buffer_manager)
+        gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager)
     : GpuBrowserCompositorOutputSurface(context,
                                         worker_context,
                                         vsync_manager,
diff --git a/content/browser/compositor/gpu_surfaceless_browser_compositor_output_surface.h b/content/browser/compositor/gpu_surfaceless_browser_compositor_output_surface.h
index a869fcc..2341219 100644
--- a/content/browser/compositor/gpu_surfaceless_browser_compositor_output_surface.h
+++ b/content/browser/compositor/gpu_surfaceless_browser_compositor_output_surface.h
@@ -7,9 +7,12 @@
 
 #include "content/browser/compositor/gpu_browser_compositor_output_surface.h"
 
+namespace gpu {
+class GpuMemoryBufferManager;
+}
+
 namespace content {
 
-class BrowserGpuMemoryBufferManager;
 class BufferQueue;
 class GLHelper;
 
@@ -25,7 +28,7 @@
           overlay_candidate_validator,
       unsigned int target,
       unsigned int internalformat,
-      BrowserGpuMemoryBufferManager* gpu_memory_buffer_manager);
+      gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager);
   ~GpuSurfacelessBrowserCompositorOutputSurface() override;
 
  private:
@@ -45,7 +48,7 @@
   unsigned int internalformat_;
   scoped_ptr<GLHelper> gl_helper_;
   scoped_ptr<BufferQueue> output_surface_;
-  BrowserGpuMemoryBufferManager* gpu_memory_buffer_manager_;
+  gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager_;
 };
 
 }  // namespace content
diff --git a/content/browser/frame_host/render_frame_host_impl.cc b/content/browser/frame_host/render_frame_host_impl.cc
index 61a3428..fdc7e33 100644
--- a/content/browser/frame_host/render_frame_host_impl.cc
+++ b/content/browser/frame_host/render_frame_host_impl.cc
@@ -2254,8 +2254,8 @@
   service_registry_->BindRemoteServiceProvider(std::move(services));
 
 #if defined(OS_ANDROID)
-  service_registry_android_.reset(
-      new ServiceRegistryAndroid(service_registry_.get()));
+  service_registry_android_ =
+      ServiceRegistryAndroid::Create(service_registry_.get());
   ServiceRegistrarAndroid::RegisterFrameHostServices(
       service_registry_android_.get());
 #endif
diff --git a/content/browser/frame_host/render_frame_host_impl.h b/content/browser/frame_host/render_frame_host_impl.h
index acef076..e4c4f08 100644
--- a/content/browser/frame_host/render_frame_host_impl.h
+++ b/content/browser/frame_host/render_frame_host_impl.h
@@ -44,7 +44,7 @@
 #include "ui/base/page_transition_types.h"
 
 #if defined(OS_ANDROID)
-#include "content/browser/mojo/service_registry_android.h"
+#include "content/public/browser/android/service_registry_android.h"
 #endif
 
 class GURL;
diff --git a/content/browser/gpu/browser_gpu_memory_buffer_manager.cc b/content/browser/gpu/browser_gpu_memory_buffer_manager.cc
index 31276dbc..7eba55f 100644
--- a/content/browser/gpu/browser_gpu_memory_buffer_manager.cc
+++ b/content/browser/gpu/browser_gpu_memory_buffer_manager.cc
@@ -239,8 +239,9 @@
 scoped_ptr<gfx::GpuMemoryBuffer>
 BrowserGpuMemoryBufferManager::AllocateGpuMemoryBuffer(const gfx::Size& size,
                                                        gfx::BufferFormat format,
-                                                       gfx::BufferUsage usage) {
-  return AllocateGpuMemoryBufferForSurface(size, format, usage, 0);
+                                                       gfx::BufferUsage usage,
+                                                       int32_t surface_id) {
+  return AllocateGpuMemoryBufferForSurface(size, format, usage, surface_id);
 }
 
 scoped_ptr<gfx::GpuMemoryBuffer>
@@ -268,16 +269,6 @@
   return std::move(request.result);
 }
 
-scoped_ptr<gfx::GpuMemoryBuffer>
-BrowserGpuMemoryBufferManager::AllocateGpuMemoryBufferForScanout(
-    const gfx::Size& size,
-    gfx::BufferFormat format,
-    int32_t surface_id) {
-  DCHECK_GT(surface_id, 0);
-  return AllocateGpuMemoryBufferForSurface(
-      size, format, gfx::BufferUsage::SCANOUT, surface_id);
-}
-
 void BrowserGpuMemoryBufferManager::AllocateGpuMemoryBufferForChildProcess(
     gfx::GpuMemoryBufferId id,
     const gfx::Size& size,
diff --git a/content/browser/gpu/browser_gpu_memory_buffer_manager.h b/content/browser/gpu/browser_gpu_memory_buffer_manager.h
index 94095f1..946ccf0e 100644
--- a/content/browser/gpu/browser_gpu_memory_buffer_manager.h
+++ b/content/browser/gpu/browser_gpu_memory_buffer_manager.h
@@ -65,7 +65,8 @@
   scoped_ptr<gfx::GpuMemoryBuffer> AllocateGpuMemoryBuffer(
       const gfx::Size& size,
       gfx::BufferFormat format,
-      gfx::BufferUsage usage) override;
+      gfx::BufferUsage usage,
+      int32_t surface_id) override;
   scoped_ptr<gfx::GpuMemoryBuffer> CreateGpuMemoryBufferFromHandle(
       const gfx::GpuMemoryBufferHandle& handle,
       const gfx::Size& size,
@@ -79,12 +80,6 @@
   bool OnMemoryDump(const base::trace_event::MemoryDumpArgs& args,
                     base::trace_event::ProcessMemoryDump* pmd) override;
 
-  // Virtual for testing.
-  virtual scoped_ptr<gfx::GpuMemoryBuffer> AllocateGpuMemoryBufferForScanout(
-      const gfx::Size& size,
-      gfx::BufferFormat format,
-      int32_t surface_id);
-
   void AllocateGpuMemoryBufferForChildProcess(
       gfx::GpuMemoryBufferId id,
       const gfx::Size& size,
diff --git a/content/browser/media/capture/aura_window_capture_machine.cc b/content/browser/media/capture/aura_window_capture_machine.cc
index 08ad2439..a56208f3 100644
--- a/content/browser/media/capture/aura_window_capture_machine.cc
+++ b/content/browser/media/capture/aura_window_capture_machine.cc
@@ -9,7 +9,6 @@
 
 #include "base/logging.h"
 #include "base/metrics/histogram.h"
-#include "base/timer/timer.h"
 #include "cc/output/copy_output_request.h"
 #include "cc/output/copy_output_result.h"
 #include "content/browser/compositor/gl_helper.h"
@@ -39,7 +38,6 @@
 
 AuraWindowCaptureMachine::AuraWindowCaptureMachine()
     : desktop_window_(NULL),
-      timer_(true, true),
       screen_capture_(false),
       weak_factory_(this) {}
 
@@ -91,14 +89,6 @@
           PowerSaveBlocker::kReasonOther,
           "DesktopCaptureDevice is running").release());
 
-  // Starts timer.
-  timer_.Start(FROM_HERE,
-               std::max(oracle_proxy_->min_capture_period(),
-                        base::TimeDelta::FromMilliseconds(media::
-                            VideoCaptureOracle::kMinTimerPollPeriodMillis)),
-               base::Bind(&AuraWindowCaptureMachine::Capture,
-                          base::Unretained(this), false));
-
   return true;
 }
 
@@ -130,12 +120,14 @@
     cursor_renderer_.reset();
   }
 
-  // Stop timer.
-  timer_.Stop();
-
   callback.Run();
 }
 
+void AuraWindowCaptureMachine::MaybeCaptureForRefresh() {
+  DCHECK_CURRENTLY_ON(BrowserThread::UI);
+  Capture(false);
+}
+
 void AuraWindowCaptureMachine::SetWindow(aura::Window* window) {
   DCHECK_CURRENTLY_ON(BrowserThread::UI);
 
@@ -179,7 +171,7 @@
   const base::TimeTicks start_time = base::TimeTicks::Now();
   const media::VideoCaptureOracle::Event event =
       dirty ? media::VideoCaptureOracle::kCompositorUpdate
-            : media::VideoCaptureOracle::kTimerPoll;
+            : media::VideoCaptureOracle::kActiveRefreshRequest;
   if (oracle_proxy_->ObserveEventAndDecideCapture(
           event, gfx::Rect(), start_time, &frame, &capture_frame_cb)) {
     scoped_ptr<cc::CopyOutputRequest> request =
diff --git a/content/browser/media/capture/aura_window_capture_machine.h b/content/browser/media/capture/aura_window_capture_machine.h
index c07c72f..6f206afe 100644
--- a/content/browser/media/capture/aura_window_capture_machine.h
+++ b/content/browser/media/capture/aura_window_capture_machine.h
@@ -8,7 +8,6 @@
 #include "base/macros.h"
 #include "base/memory/scoped_ptr.h"
 #include "base/memory/weak_ptr.h"
-#include "base/timer/timer.h"
 #include "content/browser/media/capture/cursor_renderer_aura.h"
 #include "media/capture/content/screen_capture_device_core.h"
 #include "ui/aura/window.h"
@@ -40,6 +39,7 @@
              const media::VideoCaptureParams& params,
              const base::Callback<void(bool)> callback) override;
   void Stop(const base::Closure& callback) override;
+  void MaybeCaptureForRefresh() override;
 
   // Implements aura::WindowObserver.
   void OnWindowBoundsChanged(aura::Window* window,
@@ -69,7 +69,7 @@
   void InternalStop(const base::Closure& callback);
 
   // Captures a frame.
-  // |dirty| is false for timer polls and true for compositor updates.
+  // |dirty| is false for refresh requests and true for compositor updates.
   void Capture(bool dirty);
 
   // Update capture size. Must be called on the UI thread.
@@ -105,9 +105,6 @@
   // The window associated with the desktop.
   aura::Window* desktop_window_;
 
-  // The timer that kicks off period captures.
-  base::Timer timer_;
-
   // Whether screen capturing or window capture.
   bool screen_capture_;
 
diff --git a/content/browser/media/capture/desktop_capture_device_aura.cc b/content/browser/media/capture/desktop_capture_device_aura.cc
index 39f7a07..b67f44a8 100644
--- a/content/browser/media/capture/desktop_capture_device_aura.cc
+++ b/content/browser/media/capture/desktop_capture_device_aura.cc
@@ -57,6 +57,10 @@
   core_->AllocateAndStart(params, std::move(client));
 }
 
+void DesktopCaptureDeviceAura::RequestRefreshFrame() {
+  core_->RequestRefreshFrame();
+}
+
 void DesktopCaptureDeviceAura::StopAndDeAllocate() {
   core_->StopAndDeAllocate();
 }
diff --git a/content/browser/media/capture/desktop_capture_device_aura.h b/content/browser/media/capture/desktop_capture_device_aura.h
index 82ce595..8c83a37 100644
--- a/content/browser/media/capture/desktop_capture_device_aura.h
+++ b/content/browser/media/capture/desktop_capture_device_aura.h
@@ -34,6 +34,7 @@
   // VideoCaptureDevice implementation.
   void AllocateAndStart(const media::VideoCaptureParams& params,
                         scoped_ptr<Client> client) override;
+  void RequestRefreshFrame() override;
   void StopAndDeAllocate() override;
 
  private:
diff --git a/content/browser/media/capture/web_contents_video_capture_device.cc b/content/browser/media/capture/web_contents_video_capture_device.cc
index 73ba6c5..461a211 100644
--- a/content/browser/media/capture/web_contents_video_capture_device.cc
+++ b/content/browser/media/capture/web_contents_video_capture_device.cc
@@ -183,9 +183,9 @@
 // knows how to do the capture and prepare the result for delivery.
 //
 // In practice, this means (a) installing a RenderWidgetHostFrameSubscriber in
-// the RenderWidgetHostView, to process compositor updates, and (b) running a
-// timer to possibly initiate forced, non-event-driven captures needed by
-// downstream consumers that require frame repeats of unchanged content.
+// the RenderWidgetHostView, to process compositor updates, and (b) occasionally
+// initiating forced, non-event-driven captures needed by downstream consumers
+// that request "refresh frames" of unchanged content.
 //
 // All of this happens on the UI thread, although the
 // RenderWidgetHostViewFrameSubscriber we install may be dispatching updates
@@ -207,8 +207,10 @@
       const CaptureCallback& capture_callback);
   ~ContentCaptureSubscription();
 
+  void MaybeCaptureForRefresh();
+
  private:
-  // Called on timer or mouse activity events.
+  // Called for active frame refresh requests, or mouse activity events.
   void OnEvent(FrameSubscriber* subscriber);
 
   // Maintain a weak reference to the RenderWidgetHost (via its routing ID),
@@ -218,10 +220,9 @@
   const int render_widget_id_;
 
   VideoFrameDeliveryLog delivery_log_;
-  scoped_ptr<FrameSubscriber> timer_subscriber_;
+  scoped_ptr<FrameSubscriber> refresh_subscriber_;
   scoped_ptr<FrameSubscriber> mouse_activity_subscriber_;
   CaptureCallback capture_callback_;
-  base::Timer timer_;
 
   // Responsible for tracking the cursor state and input events to make
   // decisions and then render the mouse cursor on the video frame after
@@ -266,6 +267,7 @@
   bool IsAutoThrottlingEnabled() const override {
     return auto_throttling_enabled_;
   }
+  void MaybeCaptureForRefresh() override;
 
   // Starts a copy from the backing store or the composited surface. Must be run
   // on the UI BrowserThread. |deliver_frame_cb| will be run when the operation
@@ -282,6 +284,7 @@
       const scoped_refptr<media::ThreadSafeCaptureOracle>& oracle_proxy,
       const media::VideoCaptureParams& params);
   void InternalStop(const base::Closure& callback);
+  void InternalMaybeCaptureForRefresh();
   bool IsStarted() const;
 
   // Computes the preferred size of the target RenderWidget for optimal capture.
@@ -426,8 +429,7 @@
     : render_process_id_(source.GetProcess()->GetID()),
       render_widget_id_(source.GetRoutingID()),
       delivery_log_(),
-      capture_callback_(capture_callback),
-      timer_(true, true) {
+      capture_callback_(capture_callback) {
   DCHECK_CURRENTLY_ON(BrowserThread::UI);
 
   RenderWidgetHostView* const view = source.GetView();
@@ -438,8 +440,9 @@
         WindowActivityTracker::Create(view->GetNativeView());
   }
 #endif
-  timer_subscriber_.reset(new FrameSubscriber(
-      media::VideoCaptureOracle::kTimerPoll, oracle_proxy, &delivery_log_,
+  refresh_subscriber_.reset(new FrameSubscriber(
+      media::VideoCaptureOracle::kActiveRefreshRequest, oracle_proxy,
+      &delivery_log_,
       cursor_renderer_ ? cursor_renderer_->GetWeakPtr()
                        : base::WeakPtr<CursorRenderer>(),
       window_activity_tracker_ ? window_activity_tracker_->GetWeakPtr()
@@ -464,14 +467,6 @@
     view->BeginFrameSubscription(std::move(subscriber));
   }
 
-  // Subscribe to timer events. This instance will service these as well.
-  timer_.Start(
-      FROM_HERE,
-      std::max(oracle_proxy->min_capture_period(),
-               base::TimeDelta::FromMilliseconds(
-                   media::VideoCaptureOracle::kMinTimerPollPeriodMillis)),
-      base::Bind(&ContentCaptureSubscription::OnEvent, base::Unretained(this),
-                 timer_subscriber_.get()));
   // Subscribe to mouse movement and mouse cursor update events.
   if (window_activity_tracker_) {
     window_activity_tracker_->RegisterMouseInteractionObserver(
@@ -495,6 +490,11 @@
     view->EndFrameSubscription();
 }
 
+void ContentCaptureSubscription::MaybeCaptureForRefresh() {
+  DCHECK_CURRENTLY_ON(BrowserThread::UI);
+  OnEvent(refresh_subscriber_.get());
+}
+
 void ContentCaptureSubscription::OnEvent(FrameSubscriber* subscriber) {
   DCHECK_CURRENTLY_ON(BrowserThread::UI);
   TRACE_EVENT0("gpu.capture", "ContentCaptureSubscription::OnEvent");
@@ -503,7 +503,7 @@
   RenderWidgetHostViewFrameSubscriber::DeliverFrameCallback deliver_frame_cb;
 
   const base::TimeTicks start_time = base::TimeTicks::Now();
-  DCHECK(subscriber == timer_subscriber_.get() ||
+  DCHECK(subscriber == refresh_subscriber_.get() ||
          subscriber == mouse_activity_subscriber_.get());
   if (subscriber->ShouldCaptureFrame(gfx::Rect(), start_time, &frame,
                                      &deliver_frame_cb)) {
@@ -704,6 +704,21 @@
   }
 }
 
+void WebContentsCaptureMachine::MaybeCaptureForRefresh() {
+  BrowserThread::PostTask(
+      BrowserThread::UI, FROM_HERE,
+      base::Bind(&WebContentsCaptureMachine::InternalMaybeCaptureForRefresh,
+                 // Use of Unretained() is safe here since this task must run
+                 // before InternalStop().
+                 base::Unretained(this)));
+}
+
+void WebContentsCaptureMachine::InternalMaybeCaptureForRefresh() {
+  DCHECK_CURRENTLY_ON(BrowserThread::UI);
+  if (IsStarted() && subscription_)
+    subscription_->MaybeCaptureForRefresh();
+}
+
 void WebContentsCaptureMachine::Capture(
     const base::TimeTicks& start_time,
     const scoped_refptr<media::VideoFrame>& target,
@@ -956,6 +971,10 @@
   core_->AllocateAndStart(params, std::move(client));
 }
 
+void WebContentsVideoCaptureDevice::RequestRefreshFrame() {
+  core_->RequestRefreshFrame();
+}
+
 void WebContentsVideoCaptureDevice::StopAndDeAllocate() {
   core_->StopAndDeAllocate();
 }
diff --git a/content/browser/media/capture/web_contents_video_capture_device.h b/content/browser/media/capture/web_contents_video_capture_device.h
index ab0e03a..a30557d 100644
--- a/content/browser/media/capture/web_contents_video_capture_device.h
+++ b/content/browser/media/capture/web_contents_video_capture_device.h
@@ -37,6 +37,7 @@
   // VideoCaptureDevice implementation.
   void AllocateAndStart(const media::VideoCaptureParams& params,
                         scoped_ptr<Client> client) override;
+  void RequestRefreshFrame() override;
   void StopAndDeAllocate() override;
 
  private:
diff --git a/content/browser/media/capture/web_contents_video_capture_device_unittest.cc b/content/browser/media/capture/web_contents_video_capture_device_unittest.cc
index dfa65484..d089f63 100644
--- a/content/browser/media/capture/web_contents_video_capture_device_unittest.cc
+++ b/content/browser/media/capture/web_contents_video_capture_device_unittest.cc
@@ -22,8 +22,6 @@
 #include "content/browser/renderer_host/render_view_host_factory.h"
 #include "content/browser/renderer_host/render_widget_host_impl.h"
 #include "content/browser/web_contents/web_contents_impl.h"
-#include "content/public/browser/notification_service.h"
-#include "content/public/browser/notification_types.h"
 #include "content/public/browser/render_widget_host_view_frame_subscriber.h"
 #include "content/public/browser/web_contents_media_capture_id.h"
 #include "content/public/test/mock_render_process_host.h"
@@ -60,7 +58,8 @@
 
 void DeadlineExceeded(base::Closure quit_closure) {
   if (!base::debug::BeingDebugged()) {
-    quit_closure.Run();
+    if (!quit_closure.is_null())
+      quit_closure.Run();
     FAIL() << "Deadline exceeded while waiting, quitting";
   } else {
     LOG(WARNING) << "Deadline exceeded; test would fail if debugger weren't "
@@ -94,8 +93,7 @@
   CaptureTestSourceController()
       : color_(SK_ColorMAGENTA),
         copy_result_size_(kTestWidth, kTestHeight),
-        can_copy_to_video_frame_(false),
-        use_frame_subscriber_(false) {}
+        can_copy_to_video_frame_(true) {}
 
   void SetSolidColor(SkColor color) {
     base::AutoLock guard(lock_);
@@ -136,16 +134,6 @@
     return can_copy_to_video_frame_;
   }
 
-  void SetUseFrameSubscriber(bool value) {
-    base::AutoLock guard(lock_);
-    use_frame_subscriber_ = value;
-  }
-
-  bool CanUseFrameSubscriber() {
-    base::AutoLock guard(lock_);
-    return use_frame_subscriber_;
-  }
-
   void WaitForNextCopy() {
     {
       base::AutoLock guard(lock_);
@@ -160,7 +148,6 @@
   SkColor color_;
   gfx::Size copy_result_size_;
   bool can_copy_to_video_frame_;
-  bool use_frame_subscriber_;
   base::Closure copy_done_;
 
   DISALLOW_COPY_AND_ASSIGN(CaptureTestSourceController);
@@ -487,8 +474,7 @@
  public:
   StubClientObserver()
       : error_encountered_(false),
-        wait_color_yuv_(0xcafe1950),
-        wait_size_(kTestWidth, kTestHeight) {
+        wait_color_yuv_(0xcafe1950) {
     client_.reset(new StubClient(
         base::Bind(&StubClientObserver::DidDeliverFrame,
                    base::Unretained(this)),
@@ -503,28 +489,35 @@
 
   void QuitIfConditionsMet(SkColor color, const gfx::Size& size) {
     base::AutoLock guard(lock_);
-    if (error_encountered_)
+    if (error_encountered_ || wait_color_yuv_ == kNotInterested ||
+        wait_color_yuv_ == color) {
+      last_frame_color_yuv_ = color;
+      last_frame_size_ = size;
       base::MessageLoop::current()->QuitWhenIdle();
-    else if (wait_color_yuv_ == color && wait_size_.IsEmpty())
-      base::MessageLoop::current()->QuitWhenIdle();
-    else if (wait_color_yuv_ == color && wait_size_ == size)
-      base::MessageLoop::current()->QuitWhenIdle();
+    }
   }
 
-  // Run the current loop until a frame is delivered with the |expected_color|
-  // and any non-empty frame size.
+  // Run the current loop until the next frame is delivered.  Returns the YUV
+  // color and frame size.
+  std::pair<SkColor, gfx::Size> WaitForNextFrame() {
+    {
+      base::AutoLock guard(lock_);
+      wait_color_yuv_ = kNotInterested;
+      error_encountered_ = false;
+    }
+    RunCurrentLoopWithDeadline();
+    {
+      base::AutoLock guard(lock_);
+      CHECK(!error_encountered_);
+      return std::make_pair(last_frame_color_yuv_, last_frame_size_);
+    }
+  }
+
+  // Run the current loop until a frame is delivered with the |expected_color|.
   void WaitForNextColor(SkColor expected_color) {
-    WaitForNextColorAndFrameSize(expected_color, gfx::Size());
-  }
-
-  // Run the current loop until a frame is delivered with the |expected_color|
-  // and is of the |expected_size|.
-  void WaitForNextColorAndFrameSize(SkColor expected_color,
-                                    const gfx::Size& expected_size) {
     {
       base::AutoLock guard(lock_);
       wait_color_yuv_ = ConvertRgbToYuv(expected_color);
-      wait_size_ = expected_size;
       error_encountered_ = false;
     }
     RunCurrentLoopWithDeadline();
@@ -538,7 +531,6 @@
     {
       base::AutoLock guard(lock_);
       wait_color_yuv_ = kNotInterested;
-      wait_size_ = gfx::Size();
       error_encountered_ = false;
     }
     RunCurrentLoopWithDeadline();
@@ -577,7 +569,8 @@
   base::Lock lock_;
   bool error_encountered_;
   SkColor wait_color_yuv_;
-  gfx::Size wait_size_;
+  SkColor last_frame_color_yuv_;
+  gfx::Size last_frame_size_;
   scoped_ptr<StubClient> client_;
 
   DISALLOW_COPY_AND_ASSIGN(StubClientObserver);
@@ -686,19 +679,30 @@
   }
 
   void SimulateDrawEvent() {
-    if (source()->CanUseFrameSubscriber()) {
-      // Print
-      CaptureTestView* test_view = static_cast<CaptureTestView*>(
-          web_contents_->GetRenderViewHost()->GetWidget()->GetView());
-      test_view->SimulateUpdate();
-    } else {
-      // Simulate a non-accelerated paint.
-      NotificationService::current()->Notify(
-          NOTIFICATION_RENDER_WIDGET_HOST_DID_UPDATE_BACKING_STORE,
-          Source<RenderWidgetHost>(
-              web_contents_->GetRenderViewHost()->GetWidget()),
-          NotificationService::NoDetails());
-    }
+    DCHECK_CURRENTLY_ON(BrowserThread::UI);
+
+    // Force at least one frame period's worth of time to pass. Otherwise,
+    // internal logic may decide not to capture a frame because the draw events
+    // are more frequent that kTestFramesPerSecond.
+    //
+    // TODO(miu): Instead of physically waiting, we should inject simulated
+    // clocks for testing.
+    base::RunLoop run_loop;
+    BrowserThread::PostDelayedTask(
+        BrowserThread::UI, FROM_HERE,
+        run_loop.QuitClosure(),
+        base::TimeDelta::FromMicroseconds(
+            base::Time::kMicrosecondsPerSecond / kTestFramesPerSecond));
+    run_loop.Run();
+
+    // Schedule the update to occur when the test runs the event loop (and not
+    // before expectations have been set).
+    CaptureTestView* test_view = static_cast<CaptureTestView*>(
+        web_contents_->GetRenderViewHost()->GetWidget()->GetView());
+    BrowserThread::PostTask(
+        BrowserThread::UI, FROM_HERE,
+        base::Bind(&CaptureTestView::SimulateUpdate,
+                   base::Unretained(test_view)));
   }
 
   void SimulateSourceSizeChange(const gfx::Size& size) {
@@ -717,6 +721,45 @@
         as_web_contents_impl->GetMainFrame()->GetRenderWidgetHost(), true);
   }
 
+  // Repeatedly schedules draw events and scans for frames until the output from
+  // the capture device matches the given RGB |color| and frame |size|.
+  void SimulateDrawsUntilNewFrameSizeArrives(SkColor color,
+                                             const gfx::Size& size) {
+    const base::TimeTicks start_time = base::TimeTicks::Now();
+    while ((base::TimeTicks::Now() - start_time) <
+               TestTimeouts::action_max_timeout()) {
+      SimulateDrawEvent();
+      const auto color_and_size = client_observer()->WaitForNextFrame();
+      if (color_and_size.first == ConvertRgbToYuv(color) &&
+          color_and_size.second == size) {
+        return;
+      }
+    }
+    DeadlineExceeded(base::Closure());
+  }
+
+  void SimulateRefreshFrameRequest() {
+    // Force at least three frame period's worth of time to pass. The wait is
+    // needed because refresh frame requests are only honored when drawing
+    // events, which trigger frame captures, are not occurring frequently
+    // enough.
+    //
+    // TODO(miu): Instead of physically waiting, we should inject simulated
+    // clocks for testing.
+    base::RunLoop run_loop;
+    BrowserThread::PostDelayedTask(
+        BrowserThread::UI, FROM_HERE,
+        run_loop.QuitClosure(),
+        base::TimeDelta::FromMicroseconds(
+            3 * base::Time::kMicrosecondsPerSecond / kTestFramesPerSecond));
+    run_loop.Run();
+
+    BrowserThread::PostTask(
+        BrowserThread::UI, FROM_HERE,
+        base::Bind(&media::VideoCaptureDevice::RequestRefreshFrame,
+                   base::Unretained(device_.get())));
+  }
+
   void DestroyVideoCaptureDevice() { device_.reset(); }
 
   StubClientObserver* client_observer() {
@@ -781,7 +824,9 @@
   capture_params.requested_format.frame_rate = kTestFramesPerSecond;
   capture_params.requested_format.pixel_format = media::PIXEL_FORMAT_I420;
   device()->AllocateAndStart(capture_params, client_observer()->PassClient());
-  // Do one capture to prove
+
+  // Do one capture to prove the tab is initially open and being captured
+  // normally.
   source()->SetSolidColor(SK_ColorRED);
   SimulateDrawEvent();
   ASSERT_NO_FATAL_FAILURE(client_observer()->WaitForNextColor(SK_ColorRED));
@@ -821,9 +866,9 @@
 }
 
 TEST_F(MAYBE_WebContentsVideoCaptureDeviceTest, StopWithRendererWorkToDo) {
-  // Set up the test to use RGB copies and an normal
+  // Set up the test to use RGB captures into SkBitmaps instead of YUV captures
+  // into VideoFrames.
   source()->SetCanCopyToVideoFrame(false);
-  source()->SetUseFrameSubscriber(false);
   media::VideoCaptureParams capture_params;
   capture_params.requested_format.frame_size.SetSize(kTestWidth, kTestHeight);
   capture_params.requested_format.frame_rate = kTestFramesPerSecond;
@@ -832,7 +877,7 @@
 
   base::RunLoop().RunUntilIdle();
 
-  for (int i = 0; i < 10; ++i)
+  for (int i = 0; i < 3; ++i)
     SimulateDrawEvent();
 
   ASSERT_FALSE(client_observer()->HasError());
@@ -878,8 +923,8 @@
 
 // The "happy case" test.  No scaling is needed, so we should be able to change
 // the picture emitted from the source and expect to see each delivered to the
-// consumer. The test will alternate between the three capture paths, simulating
-// falling in and out of accelerated compositing.
+// consumer. The test will alternate between the RGB/SkBitmap and YUV/VideoFrame
+// capture paths.
 TEST_F(MAYBE_WebContentsVideoCaptureDeviceTest, GoesThroughAllTheMotions) {
   media::VideoCaptureParams capture_params;
   capture_params.requested_format.frame_size.SetSize(kTestWidth, kTestHeight);
@@ -887,26 +932,14 @@
   capture_params.requested_format.pixel_format = media::PIXEL_FORMAT_I420;
   device()->AllocateAndStart(capture_params, client_observer()->PassClient());
 
-  for (int i = 0; i < 6; i++) {
+  for (int i = 0; i < 4; i++) {
     const char* name = NULL;
-    switch (i % 3) {
-      case 0:
-        source()->SetCanCopyToVideoFrame(true);
-        source()->SetUseFrameSubscriber(false);
-        name = "VideoFrame";
-        break;
-      case 1:
-        source()->SetCanCopyToVideoFrame(false);
-        source()->SetUseFrameSubscriber(true);
-        name = "Subscriber";
-        break;
-      case 2:
-        source()->SetCanCopyToVideoFrame(false);
-        source()->SetUseFrameSubscriber(false);
-        name = "SkBitmap";
-        break;
-      default:
-        FAIL();
+    if (i % 2) {
+      source()->SetCanCopyToVideoFrame(false);
+      name = "SkBitmap";
+    } else {
+      source()->SetCanCopyToVideoFrame(true);
+      name = "VideoFrame";
     }
 
     SCOPED_TRACE(base::StringPrintf("Using %s path, iteration #%d", name, i));
@@ -942,17 +975,18 @@
 
   // These frames ought to be dropped during the Render stage. Let
   // several captures to happen.
-  ASSERT_NO_FATAL_FAILURE(source()->WaitForNextCopy());
-  ASSERT_NO_FATAL_FAILURE(source()->WaitForNextCopy());
-  ASSERT_NO_FATAL_FAILURE(source()->WaitForNextCopy());
-  ASSERT_NO_FATAL_FAILURE(source()->WaitForNextCopy());
-  ASSERT_NO_FATAL_FAILURE(source()->WaitForNextCopy());
+  for (int i = 0; i < 3; ++i) {
+    SimulateDrawEvent();
+    ASSERT_NO_FATAL_FAILURE(source()->WaitForNextCopy());
+  }
 
   // Now push some good frames through; they should be processed normally.
   source()->SetCopyResultSize(kTestWidth, kTestHeight);
   source()->SetSolidColor(SK_ColorGREEN);
+  SimulateDrawEvent();
   ASSERT_NO_FATAL_FAILURE(client_observer()->WaitForNextColor(SK_ColorGREEN));
   source()->SetSolidColor(SK_ColorRED);
+  SimulateDrawEvent();
   ASSERT_NO_FATAL_FAILURE(client_observer()->WaitForNextColor(SK_ColorRED));
 
   device()->StopAndDeAllocate();
@@ -972,17 +1006,14 @@
 
   device()->AllocateAndStart(capture_params, client_observer()->PassClient());
 
-  source()->SetUseFrameSubscriber(true);
-
   // Source size equals maximum size.  Expect delivered frames to be
   // kTestWidth by kTestHeight.
   source()->SetSolidColor(SK_ColorRED);
   const float device_scale_factor = GetDeviceScaleFactor();
   SimulateSourceSizeChange(gfx::ConvertSizeToDIP(
       device_scale_factor, gfx::Size(kTestWidth, kTestHeight)));
-  SimulateDrawEvent();
-  ASSERT_NO_FATAL_FAILURE(client_observer()->WaitForNextColorAndFrameSize(
-      SK_ColorRED, gfx::Size(kTestWidth, kTestHeight)));
+  SimulateDrawsUntilNewFrameSizeArrives(
+      SK_ColorRED, gfx::Size(kTestWidth, kTestHeight));
 
   // Source size is half in both dimensions.  Expect delivered frames to be of
   // the same aspect ratio as kTestWidth by kTestHeight, but larger than the
@@ -990,27 +1021,24 @@
   source()->SetSolidColor(SK_ColorGREEN);
   SimulateSourceSizeChange(gfx::ConvertSizeToDIP(
       device_scale_factor, gfx::Size(kTestWidth / 2, kTestHeight / 2)));
-  SimulateDrawEvent();
-  ASSERT_NO_FATAL_FAILURE(client_observer()->WaitForNextColorAndFrameSize(
-      SK_ColorGREEN, gfx::Size(180 * kTestWidth / kTestHeight, 180)));
+  SimulateDrawsUntilNewFrameSizeArrives(
+      SK_ColorGREEN, gfx::Size(180 * kTestWidth / kTestHeight, 180));
 
   // Source size changes aspect ratio.  Expect delivered frames to be padded
   // in the horizontal dimension to preserve aspect ratio.
   source()->SetSolidColor(SK_ColorBLUE);
   SimulateSourceSizeChange(gfx::ConvertSizeToDIP(
       device_scale_factor, gfx::Size(kTestWidth / 2, kTestHeight)));
-  SimulateDrawEvent();
-  ASSERT_NO_FATAL_FAILURE(client_observer()->WaitForNextColorAndFrameSize(
-      SK_ColorBLUE, gfx::Size(kTestWidth, kTestHeight)));
+  SimulateDrawsUntilNewFrameSizeArrives(
+      SK_ColorBLUE, gfx::Size(kTestWidth, kTestHeight));
 
   // Source size changes aspect ratio again.  Expect delivered frames to be
   // padded in the vertical dimension to preserve aspect ratio.
   source()->SetSolidColor(SK_ColorBLACK);
   SimulateSourceSizeChange(gfx::ConvertSizeToDIP(
       device_scale_factor, gfx::Size(kTestWidth, kTestHeight / 2)));
-  SimulateDrawEvent();
-  ASSERT_NO_FATAL_FAILURE(client_observer()->WaitForNextColorAndFrameSize(
-      SK_ColorBLACK, gfx::Size(kTestWidth, kTestHeight)));
+  SimulateDrawsUntilNewFrameSizeArrives(
+      SK_ColorBLACK, gfx::Size(kTestWidth, kTestHeight));
 
   device()->StopAndDeAllocate();
 }
@@ -1029,26 +1057,22 @@
 
   device()->AllocateAndStart(capture_params, client_observer()->PassClient());
 
-  source()->SetUseFrameSubscriber(true);
-
   // Source size equals maximum size.  Expect delivered frames to be
   // kTestWidth by kTestHeight.
   source()->SetSolidColor(SK_ColorRED);
   const float device_scale_factor = GetDeviceScaleFactor();
   SimulateSourceSizeChange(gfx::ConvertSizeToDIP(
       device_scale_factor, gfx::Size(kTestWidth, kTestHeight)));
-  SimulateDrawEvent();
-  ASSERT_NO_FATAL_FAILURE(client_observer()->WaitForNextColorAndFrameSize(
-      SK_ColorRED, gfx::Size(kTestWidth, kTestHeight)));
+  SimulateDrawsUntilNewFrameSizeArrives(
+      SK_ColorRED, gfx::Size(kTestWidth, kTestHeight));
 
   // Source size is half in both dimensions.  Expect delivered frames to also
   // be half in both dimensions.
   source()->SetSolidColor(SK_ColorGREEN);
   SimulateSourceSizeChange(gfx::ConvertSizeToDIP(
       device_scale_factor, gfx::Size(kTestWidth / 2, kTestHeight / 2)));
-  SimulateDrawEvent();
-  ASSERT_NO_FATAL_FAILURE(client_observer()->WaitForNextColorAndFrameSize(
-      SK_ColorGREEN, gfx::Size(kTestWidth / 2, kTestHeight / 2)));
+  SimulateDrawsUntilNewFrameSizeArrives(
+      SK_ColorGREEN, gfx::Size(kTestWidth / 2, kTestHeight / 2));
 
   // Source size changes to something arbitrary.  Since the source size is
   // less than the maximum size, expect delivered frames to be the same size
@@ -1057,9 +1081,7 @@
   gfx::Size arbitrary_source_size(kTestWidth / 2 + 42, kTestHeight - 10);
   SimulateSourceSizeChange(gfx::ConvertSizeToDIP(device_scale_factor,
                                                  arbitrary_source_size));
-  SimulateDrawEvent();
-  ASSERT_NO_FATAL_FAILURE(client_observer()->WaitForNextColorAndFrameSize(
-      SK_ColorBLUE, arbitrary_source_size));
+  SimulateDrawsUntilNewFrameSizeArrives(SK_ColorBLUE, arbitrary_source_size);
 
   // Source size changes to something arbitrary that exceeds the maximum frame
   // size.  Since the source size exceeds the maximum size, expect delivered
@@ -1068,11 +1090,10 @@
   arbitrary_source_size = gfx::Size(kTestWidth * 2, kTestHeight / 2);
   SimulateSourceSizeChange(gfx::ConvertSizeToDIP(device_scale_factor,
                                                  arbitrary_source_size));
-  SimulateDrawEvent();
-  ASSERT_NO_FATAL_FAILURE(client_observer()->WaitForNextColorAndFrameSize(
+  SimulateDrawsUntilNewFrameSizeArrives(
       SK_ColorBLACK, gfx::Size(kTestWidth,
                                kTestWidth * arbitrary_source_size.height() /
-                                   arbitrary_source_size.width())));
+                                   arbitrary_source_size.width()));
 
   device()->StopAndDeAllocate();
 }
@@ -1171,5 +1192,36 @@
   }
 }
 
+// Tests the RequestRefreshFrame() functionality.
+TEST_F(MAYBE_WebContentsVideoCaptureDeviceTest, ProvidesRefreshFrames) {
+  media::VideoCaptureParams capture_params;
+  capture_params.requested_format.frame_size.SetSize(kTestWidth, kTestHeight);
+  capture_params.requested_format.frame_rate = kTestFramesPerSecond;
+  capture_params.requested_format.pixel_format = media::PIXEL_FORMAT_I420;
+  device()->AllocateAndStart(capture_params, client_observer()->PassClient());
+
+  // Request a refresh frame before the first frame has been drawn.  This forces
+  // a capture.
+  source()->SetSolidColor(SK_ColorRED);
+  SimulateRefreshFrameRequest();
+  ASSERT_NO_FATAL_FAILURE(client_observer()->WaitForNextColor(SK_ColorRED));
+
+  // Now, draw a frame and wait for a normal frame capture to occur.
+  source()->SetSolidColor(SK_ColorGREEN);
+  SimulateDrawEvent();
+  ASSERT_NO_FATAL_FAILURE(client_observer()->WaitForNextColor(SK_ColorGREEN));
+
+  // Now, make three more refresh frame requests. Although the source has
+  // changed to BLUE, no draw event has occurred. Therefore, expect the refresh
+  // frames to contain the content from the last drawn frame, which is GREEN.
+  source()->SetSolidColor(SK_ColorBLUE);
+  for (int i = 0; i < 3; ++i) {
+    SimulateRefreshFrameRequest();
+    ASSERT_NO_FATAL_FAILURE(client_observer()->WaitForNextColor(SK_ColorGREEN));
+  }
+
+  device()->StopAndDeAllocate();
+}
+
 }  // namespace
 }  // namespace content
diff --git a/content/browser/mojo/mojo_application_host.cc b/content/browser/mojo/mojo_application_host.cc
index 427d6b1a..c1103e15 100644
--- a/content/browser/mojo/mojo_application_host.cc
+++ b/content/browser/mojo/mojo_application_host.cc
@@ -42,8 +42,8 @@
 
 MojoApplicationHost::MojoApplicationHost() : did_activate_(false) {
 #if defined(OS_ANDROID)
-  service_registry_android_.reset(
-      new ServiceRegistryAndroid(&service_registry_));
+  service_registry_android_ =
+      ServiceRegistryAndroid::Create(&service_registry_);
 #endif
 }
 
diff --git a/content/browser/mojo/mojo_application_host.h b/content/browser/mojo/mojo_application_host.h
index f09c729..3f3387a 100644
--- a/content/browser/mojo/mojo_application_host.h
+++ b/content/browser/mojo/mojo_application_host.h
@@ -16,7 +16,7 @@
 #include "mojo/public/cpp/system/message_pipe.h"
 
 #if defined(OS_ANDROID)
-#include "content/browser/mojo/service_registry_android.h"
+#include "content/public/browser/android/service_registry_android.h"
 #endif
 
 namespace IPC {
diff --git a/content/browser/mojo/service_registrar_android.cc b/content/browser/mojo/service_registrar_android.cc
index e29d7f32..cd0cfac 100644
--- a/content/browser/mojo/service_registrar_android.cc
+++ b/content/browser/mojo/service_registrar_android.cc
@@ -6,7 +6,7 @@
 
 #include "base/android/context_utils.h"
 #include "base/android/jni_android.h"
-#include "content/browser/mojo/service_registry_android.h"
+#include "content/public/browser/android/service_registry_android.h"
 #include "jni/ServiceRegistrar_jni.h"
 
 namespace content {
diff --git a/content/browser/mojo/service_registry_android.h b/content/browser/mojo/service_registry_android.h
deleted file mode 100644
index 17d2cb0..0000000
--- a/content/browser/mojo/service_registry_android.h
+++ /dev/null
@@ -1,56 +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 CONTENT_BROWSER_MOJO_SERVICE_REGISTRY_ANDROID_H_
-#define CONTENT_BROWSER_MOJO_SERVICE_REGISTRY_ANDROID_H_
-
-#include <jni.h>
-
-#include "base/android/scoped_java_ref.h"
-#include "base/macros.h"
-#include "content/common/content_export.h"
-
-namespace content {
-
-class ServiceRegistryImpl;
-
-// Android wrapper over ServiceRegistryImpl, allowing the browser services in
-// Java to register with ServiceRegistry.java (and abstracting away the JNI
-// calls).
-class CONTENT_EXPORT ServiceRegistryAndroid {
- public:
-  static bool Register(JNIEnv* env);
-
-  explicit ServiceRegistryAndroid(ServiceRegistryImpl* service_registry);
-  virtual ~ServiceRegistryAndroid();
-
-  // Methods called from Java.
-  void AddService(
-      JNIEnv* env,
-      const base::android::JavaParamRef<jobject>& j_service_registry,
-      const base::android::JavaParamRef<jobject>& j_manager,
-      const base::android::JavaParamRef<jobject>& j_factory,
-      const base::android::JavaParamRef<jstring>& j_name);
-  void RemoveService(
-      JNIEnv* env,
-      const base::android::JavaParamRef<jobject>& j_service_registry,
-      const base::android::JavaParamRef<jstring>& j_name);
-  void ConnectToRemoteService(
-      JNIEnv* env,
-      const base::android::JavaParamRef<jobject>& j_service_registry,
-      const base::android::JavaParamRef<jstring>& j_name,
-      jint handle);
-
-  const base::android::ScopedJavaGlobalRef<jobject>& GetObj() { return obj_; }
-
- private:
-  ServiceRegistryImpl* service_registry_;
-  base::android::ScopedJavaGlobalRef<jobject> obj_;
-
-  DISALLOW_COPY_AND_ASSIGN(ServiceRegistryAndroid);
-};
-
-}  // namespace content
-
-#endif  // CONTENT_BROWSER_MOJO_SERVICE_REGISTRY_ANDROID_H_
diff --git a/content/browser/renderer_host/delegated_frame_host.cc b/content/browser/renderer_host/delegated_frame_host.cc
index ea900a8..e103e320 100644
--- a/content/browser/renderer_host/delegated_frame_host.cc
+++ b/content/browser/renderer_host/delegated_frame_host.cc
@@ -684,22 +684,19 @@
       yuv_readback_pipeline->scaler()->SrcSize() != result_rect.size() ||
       yuv_readback_pipeline->scaler()->SrcSubrect() != result_rect ||
       yuv_readback_pipeline->scaler()->DstSize() != region_in_frame.size()) {
-    GLHelper::ScalerQuality quality = GLHelper::SCALER_QUALITY_FAST;
-    std::string quality_switch = switches::kTabCaptureDownscaleQuality;
-    // If we're scaling up, we can use the "best" quality.
-    if (result_rect.size().width() < region_in_frame.size().width() &&
-        result_rect.size().height() < region_in_frame.size().height())
-      quality_switch = switches::kTabCaptureUpscaleQuality;
-
-    std::string switch_value =
-        base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
-            quality_switch);
-    if (switch_value == "fast")
-      quality = GLHelper::SCALER_QUALITY_FAST;
-    else if (switch_value == "good")
-      quality = GLHelper::SCALER_QUALITY_GOOD;
-    else if (switch_value == "best")
-      quality = GLHelper::SCALER_QUALITY_BEST;
+    // The scaler chosen here is based on performance measurements of full
+    // end-to-end systems.  When down-scaling, always use the "fast" scaler
+    // because it performs well on both low- and high- end machines, provides
+    // decent image quality, and doesn't overwhelm downstream video encoders
+    // with too much entropy (which can drastically increase CPU utilization).
+    // When up-scaling, always use "best" because the quality improvement is
+    // huge with insignificant performance penalty.  Note that this strategy
+    // differs from single-frame snapshot capture.
+    GLHelper::ScalerQuality quality =
+        ((result_rect.size().width() < region_in_frame.size().width()) &&
+         (result_rect.size().height() < region_in_frame.size().height()))
+            ? GLHelper::SCALER_QUALITY_BEST
+            : GLHelper::SCALER_QUALITY_FAST;
 
     dfh->yuv_readback_pipeline_.reset(gl_helper->CreateReadbackPipelineYUV(
         quality, result_rect.size(), result_rect, region_in_frame.size(), true,
diff --git a/content/browser/renderer_host/media/video_capture_buffer_pool.cc b/content/browser/renderer_host/media/video_capture_buffer_pool.cc
index 831c060e..6c6a654 100644
--- a/content/browser/renderer_host/media/video_capture_buffer_pool.cc
+++ b/content/browser/renderer_host/media/video_capture_buffer_pool.cc
@@ -129,7 +129,7 @@
       gpu_memory_buffers_.push_back(
           BrowserGpuMemoryBufferManager::current()->AllocateGpuMemoryBuffer(
               size, gfx::BufferFormat::R_8,
-              gfx::BufferUsage::GPU_READ_CPU_READ_WRITE));
+              gfx::BufferUsage::GPU_READ_CPU_READ_WRITE, 0 /* surface_id */));
 
       DLOG_IF(ERROR, !gpu_memory_buffers_[i]) << "Allocating GpuMemoryBuffer";
       if (!gpu_memory_buffers_[i] || !gpu_memory_buffers_[i]->Map())
@@ -374,7 +374,9 @@
       it->second->pixel_format() == format &&
       it->second->storage_type() == storage) {
     it->second->set_held_by_producer(true);
-    return last_relinquished_buffer_id_;
+    const int resurrected_buffer_id = last_relinquished_buffer_id_;
+    last_relinquished_buffer_id_ = kInvalidId;
+    return resurrected_buffer_id;
   }
 
   return kInvalidId;
diff --git a/content/browser/renderer_host/media/video_capture_buffer_pool_unittest.cc b/content/browser/renderer_host/media/video_capture_buffer_pool_unittest.cc
index f06837e..f5c3d87 100644
--- a/content/browser/renderer_host/media/video_capture_buffer_pool_unittest.cc
+++ b/content/browser/renderer_host/media/video_capture_buffer_pool_unittest.cc
@@ -107,7 +107,8 @@
     scoped_ptr<gfx::GpuMemoryBuffer> AllocateGpuMemoryBuffer(
         const gfx::Size& size,
         gfx::BufferFormat format,
-        gfx::BufferUsage usage) override {
+        gfx::BufferUsage usage,
+        int32_t surface_id) override {
       return make_scoped_ptr(new MockGpuMemoryBuffer(size));
     }
   };
diff --git a/content/browser/service_worker/service_worker_browsertest.cc b/content/browser/service_worker/service_worker_browsertest.cc
index 560272d..b8f99a4 100644
--- a/content/browser/service_worker/service_worker_browsertest.cc
+++ b/content/browser/service_worker/service_worker_browsertest.cc
@@ -11,8 +11,12 @@
 #include "base/callback.h"
 #include "base/command_line.h"
 #include "base/macros.h"
+#include "base/memory/ref_counted.h"
+#include "base/memory/scoped_ptr.h"
 #include "base/run_loop.h"
 #include "base/single_thread_task_runner.h"
+#include "base/strings/string16.h"
+#include "base/strings/stringprintf.h"
 #include "base/strings/utf_string_conversions.h"
 #include "base/thread_task_runner_handle.h"
 #include "base/time/time.h"
@@ -217,6 +221,34 @@
   return make_scoped_ptr(new net::test_server::BasicHttpResponse());
 }
 
+scoped_ptr<net::test_server::HttpResponse>
+VerifySaveDataNotInAccessControlRequestHeader(
+    const net::test_server::HttpRequest& request) {
+  // Save-Data should be present.
+  auto it = request.headers.find("Save-Data");
+  EXPECT_NE(request.headers.end(), it);
+  EXPECT_EQ("on", it->second);
+
+  scoped_ptr<net::test_server::BasicHttpResponse> http_response(
+      new net::test_server::BasicHttpResponse());
+  if (request.method == net::test_server::METHOD_OPTIONS) {
+    // Access-Control-Request-Headers should contain 'X-Custom-Header' and not
+    // contain 'Save-Data'.
+    auto acrh_iter = request.headers.find("Access-Control-Request-Headers");
+    EXPECT_NE(request.headers.end(), acrh_iter);
+    EXPECT_NE(std::string::npos, acrh_iter->second.find("x-custom-header"));
+    EXPECT_EQ(std::string::npos, acrh_iter->second.find("save-data"));
+    http_response->AddCustomHeader("Access-Control-Allow-Headers",
+                                   acrh_iter->second);
+    http_response->AddCustomHeader("Access-Control-Allow-Methods", "GET");
+    http_response->AddCustomHeader("Access-Control-Allow-Origin", "*");
+  } else {
+    http_response->AddCustomHeader("Access-Control-Allow-Origin", "*");
+    http_response->set_content("PASS");
+  }
+  return std::move(http_response);
+}
+
 // The ImportsBustMemcache test requires that the imported script
 // would naturally be cached in blink's memcache, but the embedded
 // test server doesn't produce headers that allow the blink's memcache
@@ -1116,6 +1148,52 @@
   run_loop.Run();
 }
 
+// Tests that when data saver is enabled and a cross-origin fetch by a webpage
+// is intercepted by a serviceworker, and the serviceworker does a fetch, the
+// preflight request does not have save-data in Access-Control-Request-Headers.
+IN_PROC_BROWSER_TEST_F(ServiceWorkerBrowserTest, CrossOriginFetchWithSaveData) {
+  const char kPageUrl[] = "/service_worker/fetch_cross_origin.html";
+  const char kWorkerUrl[] = "/service_worker/fetch_event_pass_through.js";
+  net::EmbeddedTestServer cross_origin_server;
+  cross_origin_server.ServeFilesFromSourceDirectory("content/test/data");
+  cross_origin_server.RegisterRequestHandler(
+      base::Bind(&VerifySaveDataNotInAccessControlRequestHeader));
+  cross_origin_server.Start();
+
+  MockContentBrowserClient content_browser_client;
+  content_browser_client.set_data_saver_enabled(true);
+  ContentBrowserClient* old_client =
+      SetBrowserClientForTesting(&content_browser_client);
+  shell()->web_contents()->GetRenderViewHost()->OnWebkitPreferencesChanged();
+  scoped_refptr<WorkerActivatedObserver> observer =
+      new WorkerActivatedObserver(wrapper());
+  observer->Init();
+  public_context()->RegisterServiceWorker(
+      embedded_test_server()->GetURL(kPageUrl),
+      embedded_test_server()->GetURL(kWorkerUrl),
+      base::Bind(&ExpectResultAndRun, true, base::Bind(&base::DoNothing)));
+  observer->Wait();
+
+  const base::string16 title = base::ASCIIToUTF16("PASS");
+  TitleWatcher title_watcher(shell()->web_contents(), title);
+  NavigateToURL(shell(),
+                embedded_test_server()->GetURL(base::StringPrintf(
+                    "%s?%s", kPageUrl,
+                    cross_origin_server.GetURL("/cross_origin_request.html")
+                        .spec()
+                        .c_str())));
+  EXPECT_EQ(title, title_watcher.WaitAndGetTitle());
+
+  SetBrowserClientForTesting(old_client);
+  shell()->Close();
+
+  base::RunLoop run_loop;
+  public_context()->UnregisterServiceWorker(
+      embedded_test_server()->GetURL(kPageUrl),
+      base::Bind(&ExpectResultAndRun, true, run_loop.QuitClosure()));
+  run_loop.Run();
+}
+
 IN_PROC_BROWSER_TEST_F(ServiceWorkerBrowserTest,
                        FetchPageWithSaveDataPassThroughOnFetch) {
   const char kPageUrl[] = "/service_worker/pass_through_fetch.html";
diff --git a/content/browser/service_worker/service_worker_cache_writer_unittest.cc b/content/browser/service_worker/service_worker_cache_writer_unittest.cc
index 492d45f2..8c88982 100644
--- a/content/browser/service_worker/service_worker_cache_writer_unittest.cc
+++ b/content/browser/service_worker/service_worker_cache_writer_unittest.cc
@@ -37,7 +37,10 @@
 // there are any expected reads that have not yet happened.
 class MockServiceWorkerResponseReader : public ServiceWorkerResponseReader {
  public:
-  MockServiceWorkerResponseReader() : ServiceWorkerResponseReader(0, nullptr) {}
+  MockServiceWorkerResponseReader()
+      : ServiceWorkerResponseReader(
+            0,
+            base::WeakPtr<AppCacheDiskCacheInterface>()) {}
   ~MockServiceWorkerResponseReader() override {}
 
   // ServiceWorkerResponseReader overrides
@@ -195,7 +198,9 @@
 class MockServiceWorkerResponseWriter : public ServiceWorkerResponseWriter {
  public:
   MockServiceWorkerResponseWriter()
-      : ServiceWorkerResponseWriter(0, nullptr),
+      : ServiceWorkerResponseWriter(
+            0,
+            base::WeakPtr<AppCacheDiskCacheInterface>()),
         info_written_(0),
         data_written_(0) {}
   ~MockServiceWorkerResponseWriter() override {}
diff --git a/content/browser/service_worker/service_worker_disk_cache.cc b/content/browser/service_worker/service_worker_disk_cache.cc
index ef8f168f..f398e61b 100644
--- a/content/browser/service_worker/service_worker_disk_cache.cc
+++ b/content/browser/service_worker/service_worker_disk_cache.cc
@@ -11,17 +11,17 @@
 
 ServiceWorkerResponseReader::ServiceWorkerResponseReader(
     int64_t resource_id,
-    ServiceWorkerDiskCache* disk_cache)
+    const base::WeakPtr<AppCacheDiskCacheInterface>& disk_cache)
     : AppCacheResponseReader(resource_id, 0, disk_cache) {}
 
 ServiceWorkerResponseWriter::ServiceWorkerResponseWriter(
     int64_t resource_id,
-    ServiceWorkerDiskCache* disk_cache)
+    const base::WeakPtr<AppCacheDiskCacheInterface>& disk_cache)
     : AppCacheResponseWriter(resource_id, 0, disk_cache) {}
 
 ServiceWorkerResponseMetadataWriter::ServiceWorkerResponseMetadataWriter(
     int64_t resource_id,
-    ServiceWorkerDiskCache* disk_cache)
+    const base::WeakPtr<AppCacheDiskCacheInterface>& disk_cache)
     : AppCacheResponseMetadataWriter(resource_id, 0, disk_cache) {}
 
 }  // namespace content
diff --git a/content/browser/service_worker/service_worker_disk_cache.h b/content/browser/service_worker/service_worker_disk_cache.h
index 90f29bc..b5ce04c 100644
--- a/content/browser/service_worker/service_worker_disk_cache.h
+++ b/content/browser/service_worker/service_worker_disk_cache.h
@@ -29,8 +29,10 @@
  protected:
   // Should only be constructed by the storage class.
   friend class ServiceWorkerStorage;
-  ServiceWorkerResponseReader(int64_t resource_id,
-                              ServiceWorkerDiskCache* disk_cache);
+
+  ServiceWorkerResponseReader(
+      int64_t resource_id,
+      const base::WeakPtr<AppCacheDiskCacheInterface>& disk_cache);
 };
 
 class CONTENT_EXPORT ServiceWorkerResponseWriter
@@ -38,8 +40,10 @@
  protected:
   // Should only be constructed by the storage class.
   friend class ServiceWorkerStorage;
-  ServiceWorkerResponseWriter(int64_t resource_id,
-                              ServiceWorkerDiskCache* disk_cache);
+
+  ServiceWorkerResponseWriter(
+      int64_t resource_id,
+      const base::WeakPtr<AppCacheDiskCacheInterface>& disk_cache);
 };
 
 class CONTENT_EXPORT ServiceWorkerResponseMetadataWriter
@@ -47,8 +51,10 @@
  protected:
   // Should only be constructed by the storage class.
   friend class ServiceWorkerStorage;
-  ServiceWorkerResponseMetadataWriter(int64_t resource_id,
-                                      ServiceWorkerDiskCache* disk_cache);
+
+  ServiceWorkerResponseMetadataWriter(
+      int64_t resource_id,
+      const base::WeakPtr<AppCacheDiskCacheInterface>& disk_cache);
 };
 
 }  // namespace content
diff --git a/content/browser/service_worker/service_worker_storage.cc b/content/browser/service_worker/service_worker_storage.cc
index 13e39e4..ddb1e647 100644
--- a/content/browser/service_worker/service_worker_storage.cc
+++ b/content/browser/service_worker/service_worker_storage.cc
@@ -520,19 +520,19 @@
 scoped_ptr<ServiceWorkerResponseReader>
 ServiceWorkerStorage::CreateResponseReader(int64_t resource_id) {
   return make_scoped_ptr(
-      new ServiceWorkerResponseReader(resource_id, disk_cache()));
+      new ServiceWorkerResponseReader(resource_id, disk_cache()->GetWeakPtr()));
 }
 
 scoped_ptr<ServiceWorkerResponseWriter>
 ServiceWorkerStorage::CreateResponseWriter(int64_t resource_id) {
   return make_scoped_ptr(
-      new ServiceWorkerResponseWriter(resource_id, disk_cache()));
+      new ServiceWorkerResponseWriter(resource_id, disk_cache()->GetWeakPtr()));
 }
 
 scoped_ptr<ServiceWorkerResponseMetadataWriter>
 ServiceWorkerStorage::CreateResponseMetadataWriter(int64_t resource_id) {
-  return make_scoped_ptr(
-      new ServiceWorkerResponseMetadataWriter(resource_id, disk_cache()));
+  return make_scoped_ptr(new ServiceWorkerResponseMetadataWriter(
+      resource_id, disk_cache()->GetWeakPtr()));
 }
 
 void ServiceWorkerStorage::StoreUncommittedResourceId(int64_t resource_id) {
diff --git a/content/browser/site_instance_impl.h b/content/browser/site_instance_impl.h
index 935fc29..9089a02a 100644
--- a/content/browser/site_instance_impl.h
+++ b/content/browser/site_instance_impl.h
@@ -20,8 +20,8 @@
 class BrowsingInstance;
 class RenderProcessHostFactory;
 
-class CONTENT_EXPORT SiteInstanceImpl : public SiteInstance,
-                                        public RenderProcessHostObserver {
+class CONTENT_EXPORT SiteInstanceImpl final : public SiteInstance,
+                                              public RenderProcessHostObserver {
  public:
   class CONTENT_EXPORT Observer {
    public:
@@ -129,23 +129,16 @@
   static bool DoesSiteRequireDedicatedProcess(BrowserContext* browser_context,
                                               const GURL& effective_url);
 
- protected:
+ private:
   friend class BrowsingInstance;
+  friend class SiteInstanceTestBrowserClient;
 
-  // Virtual to allow tests to extend it.
-  ~SiteInstanceImpl() override;
-
-  // Create a new SiteInstance.  Protected to give access to BrowsingInstance
-  // and tests; most callers should use Create or GetRelatedSiteInstance
-  // instead.
+  // Create a new SiteInstance.  Only BrowsingInstance should call this
+  // directly; clients should use Create() or GetRelatedSiteInstance() instead.
   explicit SiteInstanceImpl(BrowsingInstance* browsing_instance);
 
-  // Only BrowsingInstance should call this.
-  void set_is_default_subframe_site_instance() {
-    is_default_subframe_site_instance_ = true;
-  }
+  ~SiteInstanceImpl() override;
 
- private:
   // RenderProcessHostObserver implementation.
   void RenderProcessHostDestroyed(RenderProcessHost* host) override;
   void RenderProcessWillExit(RenderProcessHost* host) override;
@@ -156,6 +149,10 @@
   // Used to restrict a process' origin access rights.
   void LockToOrigin();
 
+  void set_is_default_subframe_site_instance() {
+    is_default_subframe_site_instance_ = true;
+  }
+
   // An object used to construct RenderProcessHosts.
   static const RenderProcessHostFactory* g_render_process_host_factory_;
 
diff --git a/content/browser/site_instance_impl_unittest.cc b/content/browser/site_instance_impl_unittest.cc
index f2cd603..18cf06f 100644
--- a/content/browser/site_instance_impl_unittest.cc
+++ b/content/browser/site_instance_impl_unittest.cc
@@ -34,14 +34,15 @@
 #include "url/url_util.h"
 
 namespace content {
-namespace {
 
 const char kPrivilegedScheme[] = "privileged";
 
 class SiteInstanceTestBrowserClient : public TestContentBrowserClient {
  public:
-  SiteInstanceTestBrowserClient()
-      : privileged_process_id_(-1) {
+  explicit SiteInstanceTestBrowserClient()
+      : privileged_process_id_(-1),
+        site_instance_delete_count_(0),
+        browsing_instance_delete_count_(0) {
     WebUIControllerFactory::RegisterFactory(
         ContentWebUIControllerFactory::GetInstance());
   }
@@ -61,8 +62,32 @@
     privileged_process_id_ = process_id;
   }
 
+  void SiteInstanceDeleting(content::SiteInstance* site_instance) override {
+    site_instance_delete_count_++;
+    // Infer deletion of the browsing instance.
+    if (static_cast<SiteInstanceImpl*>(site_instance)
+            ->browsing_instance_->HasOneRef()) {
+      browsing_instance_delete_count_++;
+    }
+  }
+
+  int GetAndClearSiteInstanceDeleteCount() {
+    int result = site_instance_delete_count_;
+    site_instance_delete_count_ = 0;
+    return result;
+  }
+
+  int GetAndClearBrowsingInstanceDeleteCount() {
+    int result = browsing_instance_delete_count_;
+    browsing_instance_delete_count_ = 0;
+    return result;
+  }
+
  private:
   int privileged_process_id_;
+
+  int site_instance_delete_count_;
+  int browsing_instance_delete_count_;
 };
 
 class SiteInstanceTest : public testing::Test {
@@ -72,8 +97,7 @@
         file_user_blocking_thread_(BrowserThread::FILE_USER_BLOCKING,
                                    &message_loop_),
         io_thread_(BrowserThread::IO, &message_loop_),
-        old_browser_client_(NULL) {
-  }
+        old_browser_client_(nullptr) {}
 
   void SetUp() override {
     old_browser_client_ = SetBrowserClientForTesting(&browser_client_);
@@ -88,7 +112,7 @@
     EXPECT_TRUE(RenderProcessHost::AllHostsIterator().IsAtEnd());
 
     SetBrowserClientForTesting(old_browser_client_);
-    SiteInstanceImpl::set_render_process_host_factory(NULL);
+    SiteInstanceImpl::set_render_process_host_factory(nullptr);
 
     // http://crbug.com/143565 found SiteInstanceTest leaking an
     // AppCacheDatabase. This happens because some part of the test indirectly
@@ -114,6 +138,8 @@
     message_loop_.RunUntilIdle();
   }
 
+  SiteInstanceTestBrowserClient* browser_client() { return &browser_client_; }
+
  private:
   base::MessageLoopForUI message_loop_;
   TestBrowserThread ui_thread_;
@@ -125,64 +151,16 @@
   MockRenderProcessHostFactory rph_factory_;
 };
 
-// Subclass of BrowsingInstance that updates a counter when deleted and
-// returns TestSiteInstances from GetSiteInstanceForURL.
-class TestBrowsingInstance : public BrowsingInstance {
- public:
-  TestBrowsingInstance(BrowserContext* browser_context, int* delete_counter)
-      : BrowsingInstance(browser_context),
-        delete_counter_(delete_counter) {
-  }
-
-  // Make a few methods public for tests.
-  using BrowsingInstance::browser_context;
-  using BrowsingInstance::HasSiteInstance;
-  using BrowsingInstance::GetSiteInstanceForURL;
-  using BrowsingInstance::RegisterSiteInstance;
-  using BrowsingInstance::UnregisterSiteInstance;
-
- private:
-  ~TestBrowsingInstance() override { (*delete_counter_)++; }
-
-  int* delete_counter_;
-};
-
-// Subclass of SiteInstanceImpl that updates a counter when deleted.
-class TestSiteInstance : public SiteInstanceImpl {
- public:
-  static TestSiteInstance* CreateTestSiteInstance(
-      BrowserContext* browser_context,
-      int* site_delete_counter,
-      int* browsing_delete_counter) {
-    TestBrowsingInstance* browsing_instance =
-        new TestBrowsingInstance(browser_context, browsing_delete_counter);
-    return new TestSiteInstance(browsing_instance, site_delete_counter);
-  }
-
- private:
-  TestSiteInstance(BrowsingInstance* browsing_instance, int* delete_counter)
-    : SiteInstanceImpl(browsing_instance), delete_counter_(delete_counter) {}
-  ~TestSiteInstance() override { (*delete_counter_)++; }
-
-  int* delete_counter_;
-};
-
-}  // namespace
-
 // Test to ensure no memory leaks for SiteInstance objects.
 TEST_F(SiteInstanceTest, SiteInstanceDestructor) {
   // The existence of this object will cause WebContentsImpl to create our
   // test one instead of the real one.
   RenderViewHostTestEnabler rvh_test_enabler;
-  int site_delete_counter = 0;
-  int browsing_delete_counter = 0;
   const GURL url("test:foo");
 
   // Ensure that instances are deleted when their NavigationEntries are gone.
-  TestSiteInstance* instance =
-      TestSiteInstance::CreateTestSiteInstance(NULL, &site_delete_counter,
-                                               &browsing_delete_counter);
-  EXPECT_EQ(0, site_delete_counter);
+  scoped_refptr<SiteInstanceImpl> instance = SiteInstanceImpl::Create(nullptr);
+  EXPECT_EQ(0, browser_client()->GetAndClearSiteInstanceDeleteCount());
 
   NavigationEntryImpl* e1 = new NavigationEntryImpl(
       instance, 0, url, Referrer(), base::string16(), ui::PAGE_TRANSITION_LINK,
@@ -190,43 +168,45 @@
 
   // Redundantly setting e1's SiteInstance shouldn't affect the ref count.
   e1->set_site_instance(instance);
-  EXPECT_EQ(0, site_delete_counter);
+  EXPECT_EQ(0, browser_client()->GetAndClearSiteInstanceDeleteCount());
+  EXPECT_EQ(0, browser_client()->GetAndClearBrowsingInstanceDeleteCount());
 
   // Add a second reference
   NavigationEntryImpl* e2 = new NavigationEntryImpl(
       instance, 0, url, Referrer(), base::string16(), ui::PAGE_TRANSITION_LINK,
       false);
 
+  instance = nullptr;
+  EXPECT_EQ(0, browser_client()->GetAndClearSiteInstanceDeleteCount());
+  EXPECT_EQ(0, browser_client()->GetAndClearBrowsingInstanceDeleteCount());
+
   // Now delete both entries and be sure the SiteInstance goes away.
   delete e1;
-  EXPECT_EQ(0, site_delete_counter);
-  EXPECT_EQ(0, browsing_delete_counter);
+  EXPECT_EQ(0, browser_client()->GetAndClearSiteInstanceDeleteCount());
+  EXPECT_EQ(0, browser_client()->GetAndClearBrowsingInstanceDeleteCount());
   delete e2;
-  EXPECT_EQ(1, site_delete_counter);
   // instance is now deleted
-  EXPECT_EQ(1, browsing_delete_counter);
+  EXPECT_EQ(1, browser_client()->GetAndClearSiteInstanceDeleteCount());
+  EXPECT_EQ(1, browser_client()->GetAndClearBrowsingInstanceDeleteCount());
   // browsing_instance is now deleted
 
   // Ensure that instances are deleted when their RenderViewHosts are gone.
   scoped_ptr<TestBrowserContext> browser_context(new TestBrowserContext());
-  instance =
-      TestSiteInstance::CreateTestSiteInstance(browser_context.get(),
-                                               &site_delete_counter,
-                                               &browsing_delete_counter);
   {
     scoped_ptr<WebContentsImpl> web_contents(static_cast<WebContentsImpl*>(
         WebContents::Create(WebContents::CreateParams(
-            browser_context.get(), instance))));
-    EXPECT_EQ(1, site_delete_counter);
-    EXPECT_EQ(1, browsing_delete_counter);
+            browser_context.get(),
+            SiteInstance::Create(browser_context.get())))));
+    EXPECT_EQ(0, browser_client()->GetAndClearSiteInstanceDeleteCount());
+    EXPECT_EQ(0, browser_client()->GetAndClearBrowsingInstanceDeleteCount());
   }
 
   // Make sure that we flush any messages related to the above WebContentsImpl
   // destruction.
   DrainMessageLoops();
 
-  EXPECT_EQ(2, site_delete_counter);
-  EXPECT_EQ(2, browsing_delete_counter);
+  EXPECT_EQ(1, browser_client()->GetAndClearSiteInstanceDeleteCount());
+  EXPECT_EQ(1, browser_client()->GetAndClearBrowsingInstanceDeleteCount());
   // contents is now deleted, along with instance and browsing_instance
 }
 
@@ -234,40 +214,31 @@
 // SiteInstances can be changed afterwards.  Also tests that the ref counts are
 // updated properly after the change.
 TEST_F(SiteInstanceTest, CloneNavigationEntry) {
-  int site_delete_counter1 = 0;
-  int site_delete_counter2 = 0;
-  int browsing_delete_counter = 0;
   const GURL url("test:foo");
 
-  SiteInstanceImpl* instance1 =
-      TestSiteInstance::CreateTestSiteInstance(NULL, &site_delete_counter1,
-                                               &browsing_delete_counter);
-  SiteInstanceImpl* instance2 =
-      TestSiteInstance::CreateTestSiteInstance(NULL, &site_delete_counter2,
-                                               &browsing_delete_counter);
-
   scoped_ptr<NavigationEntryImpl> e1 = make_scoped_ptr(new NavigationEntryImpl(
-      instance1, 0, url, Referrer(), base::string16(), ui::PAGE_TRANSITION_LINK,
-      false));
+      SiteInstanceImpl::Create(nullptr), 0, url, Referrer(), base::string16(),
+      ui::PAGE_TRANSITION_LINK, false));
+
   // Clone the entry.
   scoped_ptr<NavigationEntryImpl> e2 = e1->Clone();
 
   // Should be able to change the SiteInstance of the cloned entry.
-  e2->set_site_instance(instance2);
+  e2->set_site_instance(SiteInstanceImpl::Create(nullptr));
 
-  // The first SiteInstance should go away after resetting e1, since e2 should
-  // no longer be referencing it.
+  EXPECT_EQ(0, browser_client()->GetAndClearSiteInstanceDeleteCount());
+  EXPECT_EQ(0, browser_client()->GetAndClearBrowsingInstanceDeleteCount());
+
+  // The first SiteInstance and BrowsingInstance should go away after resetting
+  // e1, since e2 should no longer be referencing it.
   e1.reset();
-  EXPECT_EQ(1, site_delete_counter1);
-  EXPECT_EQ(0, site_delete_counter2);
+  EXPECT_EQ(1, browser_client()->GetAndClearSiteInstanceDeleteCount());
+  EXPECT_EQ(1, browser_client()->GetAndClearBrowsingInstanceDeleteCount());
 
   // The second SiteInstance should go away after resetting e2.
   e2.reset();
-  EXPECT_EQ(1, site_delete_counter1);
-  EXPECT_EQ(1, site_delete_counter2);
-
-  // Both BrowsingInstances are also now deleted.
-  EXPECT_EQ(2, browsing_delete_counter);
+  EXPECT_EQ(1, browser_client()->GetAndClearSiteInstanceDeleteCount());
+  EXPECT_EQ(1, browser_client()->GetAndClearBrowsingInstanceDeleteCount());
 
   DrainMessageLoops();
 }
@@ -280,13 +251,13 @@
   scoped_refptr<SiteInstanceImpl> instance(
       SiteInstanceImpl::Create(browser_context.get()));
   host1.reset(instance->GetProcess());
-  EXPECT_TRUE(host1.get() != NULL);
+  EXPECT_TRUE(host1.get() != nullptr);
 
   // Ensure that GetProcess creates a new process.
   scoped_refptr<SiteInstanceImpl> instance2(
       SiteInstanceImpl::Create(browser_context.get()));
   scoped_ptr<RenderProcessHost> host2(instance2->GetProcess());
-  EXPECT_TRUE(host2.get() != NULL);
+  EXPECT_TRUE(host2.get() != nullptr);
   EXPECT_NE(host1.get(), host2.get());
 
   DrainMessageLoops();
@@ -294,7 +265,7 @@
 
 // Test to ensure SetSite and site() work properly.
 TEST_F(SiteInstanceTest, SetSite) {
-  scoped_refptr<SiteInstanceImpl> instance(SiteInstanceImpl::Create(NULL));
+  scoped_refptr<SiteInstanceImpl> instance(SiteInstanceImpl::Create(nullptr));
   EXPECT_FALSE(instance->HasSite());
   EXPECT_TRUE(instance->GetSiteURL().is_empty());
 
@@ -310,45 +281,45 @@
 TEST_F(SiteInstanceTest, GetSiteForURL) {
   // Pages are irrelevant.
   GURL test_url = GURL("http://www.google.com/index.html");
-  GURL site_url = SiteInstanceImpl::GetSiteForURL(NULL, test_url);
+  GURL site_url = SiteInstanceImpl::GetSiteForURL(nullptr, test_url);
   EXPECT_EQ(GURL("http://google.com"), site_url);
   EXPECT_EQ("http", site_url.scheme());
   EXPECT_EQ("google.com", site_url.host());
 
   // Ports are irrlevant.
   test_url = GURL("https://www.google.com:8080");
-  site_url = SiteInstanceImpl::GetSiteForURL(NULL, test_url);
+  site_url = SiteInstanceImpl::GetSiteForURL(nullptr, test_url);
   EXPECT_EQ(GURL("https://google.com"), site_url);
 
   // Hostnames without TLDs are ok.
   test_url = GURL("http://foo/a.html");
-  site_url = SiteInstanceImpl::GetSiteForURL(NULL, test_url);
+  site_url = SiteInstanceImpl::GetSiteForURL(nullptr, test_url);
   EXPECT_EQ(GURL("http://foo"), site_url);
   EXPECT_EQ("foo", site_url.host());
 
   // File URLs should include the scheme.
   test_url = GURL("file:///C:/Downloads/");
-  site_url = SiteInstanceImpl::GetSiteForURL(NULL, test_url);
+  site_url = SiteInstanceImpl::GetSiteForURL(nullptr, test_url);
   EXPECT_EQ(GURL("file:"), site_url);
   EXPECT_EQ("file", site_url.scheme());
   EXPECT_FALSE(site_url.has_host());
 
   // Some file URLs have hosts in the path.
   test_url = GURL("file://server/path");
-  site_url = SiteInstanceImpl::GetSiteForURL(NULL, test_url);
+  site_url = SiteInstanceImpl::GetSiteForURL(nullptr, test_url);
   EXPECT_EQ(GURL("file://server"), site_url);
   EXPECT_EQ("server", site_url.host());
 
   // Data URLs should include the scheme.
   test_url = GURL("data:text/html,foo");
-  site_url = SiteInstanceImpl::GetSiteForURL(NULL, test_url);
+  site_url = SiteInstanceImpl::GetSiteForURL(nullptr, test_url);
   EXPECT_EQ(GURL("data:"), site_url);
   EXPECT_EQ("data", site_url.scheme());
   EXPECT_FALSE(site_url.has_host());
 
   // Javascript URLs should include the scheme.
   test_url = GURL("javascript:foo();");
-  site_url = SiteInstanceImpl::GetSiteForURL(NULL, test_url);
+  site_url = SiteInstanceImpl::GetSiteForURL(nullptr, test_url);
   EXPECT_EQ(GURL("javascript:"), site_url);
   EXPECT_EQ("javascript", site_url.scheme());
   EXPECT_FALSE(site_url.has_host());
@@ -358,7 +329,7 @@
   std::string guest_url(kGuestScheme);
   guest_url.append("://abc123/path");
   test_url = GURL(guest_url);
-  site_url = SiteInstanceImpl::GetSiteForURL(NULL, test_url);
+  site_url = SiteInstanceImpl::GetSiteForURL(nullptr, test_url);
   EXPECT_EQ(test_url, site_url);
 
   DrainMessageLoops();
@@ -376,29 +347,31 @@
   GURL url_blank = GURL(url::kAboutBlankURL);
 
   // Same scheme and port -> same site.
-  EXPECT_TRUE(SiteInstance::IsSameWebSite(NULL, url_foo, url_foo2));
+  EXPECT_TRUE(SiteInstance::IsSameWebSite(nullptr, url_foo, url_foo2));
 
   // Different scheme -> different site.
-  EXPECT_FALSE(SiteInstance::IsSameWebSite(NULL, url_foo, url_foo_https));
+  EXPECT_FALSE(SiteInstance::IsSameWebSite(nullptr, url_foo, url_foo_https));
 
   // Different port -> same site.
   // (Changes to document.domain make renderer ignore the port.)
-  EXPECT_TRUE(SiteInstance::IsSameWebSite(NULL, url_foo, url_foo_port));
+  EXPECT_TRUE(SiteInstance::IsSameWebSite(nullptr, url_foo, url_foo_port));
 
   // JavaScript links should be considered same site for anything.
-  EXPECT_TRUE(SiteInstance::IsSameWebSite(NULL, url_javascript, url_foo));
-  EXPECT_TRUE(SiteInstance::IsSameWebSite(NULL, url_javascript, url_foo_https));
-  EXPECT_TRUE(SiteInstance::IsSameWebSite(NULL, url_javascript, url_foo_port));
+  EXPECT_TRUE(SiteInstance::IsSameWebSite(nullptr, url_javascript, url_foo));
+  EXPECT_TRUE(
+      SiteInstance::IsSameWebSite(nullptr, url_javascript, url_foo_https));
+  EXPECT_TRUE(
+      SiteInstance::IsSameWebSite(nullptr, url_javascript, url_foo_port));
 
   // Navigating to a blank page is considered the same site.
-  EXPECT_TRUE(SiteInstance::IsSameWebSite(NULL, url_foo, url_blank));
-  EXPECT_TRUE(SiteInstance::IsSameWebSite(NULL, url_foo_https, url_blank));
-  EXPECT_TRUE(SiteInstance::IsSameWebSite(NULL, url_foo_port, url_blank));
+  EXPECT_TRUE(SiteInstance::IsSameWebSite(nullptr, url_foo, url_blank));
+  EXPECT_TRUE(SiteInstance::IsSameWebSite(nullptr, url_foo_https, url_blank));
+  EXPECT_TRUE(SiteInstance::IsSameWebSite(nullptr, url_foo_port, url_blank));
 
   // Navigating from a blank site is not considered to be the same site.
-  EXPECT_FALSE(SiteInstance::IsSameWebSite(NULL, url_blank, url_foo));
-  EXPECT_FALSE(SiteInstance::IsSameWebSite(NULL, url_blank, url_foo_https));
-  EXPECT_FALSE(SiteInstance::IsSameWebSite(NULL, url_blank, url_foo_port));
+  EXPECT_FALSE(SiteInstance::IsSameWebSite(nullptr, url_blank, url_foo));
+  EXPECT_FALSE(SiteInstance::IsSameWebSite(nullptr, url_blank, url_foo_https));
+  EXPECT_FALSE(SiteInstance::IsSameWebSite(nullptr, url_blank, url_foo_port));
 
   DrainMessageLoops();
 }
@@ -408,15 +381,14 @@
 TEST_F(SiteInstanceTest, OneSiteInstancePerSite) {
   ASSERT_FALSE(base::CommandLine::ForCurrentProcess()->HasSwitch(
       switches::kProcessPerSite));
-  int delete_counter = 0;
   scoped_ptr<TestBrowserContext> browser_context(new TestBrowserContext());
-  TestBrowsingInstance* browsing_instance =
-      new TestBrowsingInstance(browser_context.get(), &delete_counter);
+  BrowsingInstance* browsing_instance =
+      new BrowsingInstance(browser_context.get());
 
   const GURL url_a1("http://www.google.com/1.html");
   scoped_refptr<SiteInstanceImpl> site_instance_a1(
       browsing_instance->GetSiteInstanceForURL(url_a1));
-  EXPECT_TRUE(site_instance_a1.get() != NULL);
+  EXPECT_TRUE(site_instance_a1.get() != nullptr);
 
   // A separate site should create a separate SiteInstance.
   const GURL url_b1("http://www.yahoo.com/");
@@ -440,8 +412,8 @@
 
   // A visit to the original site in a new BrowsingInstance (same or different
   // browser context) should return a different SiteInstance.
-  TestBrowsingInstance* browsing_instance2 =
-      new TestBrowsingInstance(browser_context.get(), &delete_counter);
+  BrowsingInstance* browsing_instance2 =
+      new BrowsingInstance(browser_context.get());
   // Ensure the new SiteInstance is ref counted so that it gets deleted.
   scoped_refptr<SiteInstanceImpl> site_instance_a2_2(
       browsing_instance2->GetSiteInstanceForURL(url_a2));
@@ -480,15 +452,14 @@
 TEST_F(SiteInstanceTest, OneSiteInstancePerSiteInBrowserContext) {
   base::CommandLine::ForCurrentProcess()->AppendSwitch(
       switches::kProcessPerSite);
-  int delete_counter = 0;
   scoped_ptr<TestBrowserContext> browser_context(new TestBrowserContext());
-  TestBrowsingInstance* browsing_instance =
-      new TestBrowsingInstance(browser_context.get(), &delete_counter);
+  scoped_refptr<BrowsingInstance> browsing_instance =
+      new BrowsingInstance(browser_context.get());
 
   const GURL url_a1("http://www.google.com/1.html");
   scoped_refptr<SiteInstanceImpl> site_instance_a1(
       browsing_instance->GetSiteInstanceForURL(url_a1));
-  EXPECT_TRUE(site_instance_a1.get() != NULL);
+  EXPECT_TRUE(site_instance_a1.get() != nullptr);
   scoped_ptr<RenderProcessHost> process_a1(site_instance_a1->GetProcess());
 
   // A separate site should create a separate SiteInstance.
@@ -512,22 +483,22 @@
 
   // A visit to the original site in a new BrowsingInstance (same browser
   // context) should return a different SiteInstance with the same process.
-  TestBrowsingInstance* browsing_instance2 =
-      new TestBrowsingInstance(browser_context.get(), &delete_counter);
+  BrowsingInstance* browsing_instance2 =
+      new BrowsingInstance(browser_context.get());
   scoped_refptr<SiteInstanceImpl> site_instance_a1_2(
       browsing_instance2->GetSiteInstanceForURL(url_a1));
-  EXPECT_TRUE(site_instance_a1.get() != NULL);
+  EXPECT_TRUE(site_instance_a1.get() != nullptr);
   EXPECT_NE(site_instance_a1.get(), site_instance_a1_2.get());
   EXPECT_EQ(process_a1.get(), site_instance_a1_2->GetProcess());
 
   // A visit to the original site in a new BrowsingInstance (different browser
   // context) should return a different SiteInstance with a different process.
   scoped_ptr<TestBrowserContext> browser_context2(new TestBrowserContext());
-  TestBrowsingInstance* browsing_instance3 =
-      new TestBrowsingInstance(browser_context2.get(), &delete_counter);
+  BrowsingInstance* browsing_instance3 =
+      new BrowsingInstance(browser_context2.get());
   scoped_refptr<SiteInstanceImpl> site_instance_a2_3(
       browsing_instance3->GetSiteInstanceForURL(url_a2));
-  EXPECT_TRUE(site_instance_a2_3.get() != NULL);
+  EXPECT_TRUE(site_instance_a2_3.get() != nullptr);
   scoped_ptr<RenderProcessHost> process_a2_3(site_instance_a2_3->GetProcess());
   EXPECT_NE(site_instance_a1.get(), site_instance_a2_3.get());
   EXPECT_NE(process_a1.get(), process_a2_3.get());
@@ -644,7 +615,7 @@
   // The call to GetProcess actually creates a new real process, which works
   // fine, but might be a cause for problems in different contexts.
   host.reset(instance->GetProcess());
-  EXPECT_TRUE(host.get() != NULL);
+  EXPECT_TRUE(host.get() != nullptr);
   EXPECT_TRUE(instance->HasProcess());
 
   EXPECT_FALSE(instance->HasWrongProcessForURL(GURL("http://evernote.com")));
@@ -702,7 +673,7 @@
   // The call to GetProcess actually creates a new real process, which works
   // fine, but might be a cause for problems in different contexts.
   host.reset(instance->GetProcess());
-  EXPECT_TRUE(host.get() != NULL);
+  EXPECT_TRUE(host.get() != nullptr);
   EXPECT_TRUE(instance->HasProcess());
 
   EXPECT_FALSE(instance->HasWrongProcessForURL(GURL("http://evernote.com")));
@@ -734,7 +705,7 @@
 
   // The call to GetProcess actually creates a new real process.
   host.reset(instance->GetProcess());
-  EXPECT_TRUE(host.get() != NULL);
+  EXPECT_TRUE(host.get() != nullptr);
   EXPECT_TRUE(instance->HasProcess());
 
   // Without bindings, this should look like the wrong process.
@@ -747,7 +718,7 @@
       SiteInstanceImpl::Create(browser_context.get()));
   instance2->SetSite(webui_url);
   host2.reset(instance2->GetProcess());
-  EXPECT_TRUE(host2.get() != NULL);
+  EXPECT_TRUE(host2.get() != nullptr);
   EXPECT_TRUE(instance2->HasProcess());
   EXPECT_NE(host.get(), host2.get());
 
@@ -775,4 +746,53 @@
   DrainMessageLoops();
 }
 
+TEST_F(SiteInstanceTest, DefaultSubframeSiteInstance) {
+  if (AreAllSitesIsolatedForTesting())
+    return;  // --top-document-isolation is not possible.
+
+  base::CommandLine::ForCurrentProcess()->AppendSwitch(
+      switches::kTopDocumentIsolation);
+
+  scoped_ptr<TestBrowserContext> browser_context(new TestBrowserContext());
+  scoped_refptr<SiteInstanceImpl> main_instance =
+      SiteInstanceImpl::Create(browser_context.get());
+  scoped_refptr<SiteInstanceImpl> subframe_instance =
+      main_instance->GetDefaultSubframeSiteInstance();
+  int subframe_instance_id = subframe_instance->GetId();
+
+  EXPECT_NE(main_instance, subframe_instance);
+  EXPECT_EQ(subframe_instance, main_instance->GetDefaultSubframeSiteInstance());
+  EXPECT_FALSE(main_instance->is_default_subframe_site_instance());
+  EXPECT_TRUE(subframe_instance->is_default_subframe_site_instance());
+
+  EXPECT_EQ(0, browser_client()->GetAndClearSiteInstanceDeleteCount());
+  EXPECT_EQ(0, browser_client()->GetAndClearBrowsingInstanceDeleteCount());
+
+  // Free the subframe instance.
+  subframe_instance = nullptr;
+  EXPECT_EQ(1, browser_client()->GetAndClearSiteInstanceDeleteCount());
+  EXPECT_EQ(0, browser_client()->GetAndClearBrowsingInstanceDeleteCount());
+
+  // Calling GetDefaultSubframeSiteInstance again should return a new
+  // SiteInstance with a different ID from the original.
+  subframe_instance = main_instance->GetDefaultSubframeSiteInstance();
+  EXPECT_NE(subframe_instance->GetId(), subframe_instance_id);
+  EXPECT_FALSE(main_instance->is_default_subframe_site_instance());
+  EXPECT_TRUE(subframe_instance->is_default_subframe_site_instance());
+  EXPECT_EQ(subframe_instance->GetDefaultSubframeSiteInstance(),
+            subframe_instance);
+  EXPECT_EQ(0, browser_client()->GetAndClearSiteInstanceDeleteCount());
+  EXPECT_EQ(0, browser_client()->GetAndClearBrowsingInstanceDeleteCount());
+
+  // Free the main instance.
+  main_instance = nullptr;
+  EXPECT_EQ(1, browser_client()->GetAndClearSiteInstanceDeleteCount());
+  EXPECT_EQ(0, browser_client()->GetAndClearBrowsingInstanceDeleteCount());
+
+  // Free the subframe instance, which should free the browsing instance.
+  subframe_instance = nullptr;
+  EXPECT_EQ(1, browser_client()->GetAndClearSiteInstanceDeleteCount());
+  EXPECT_EQ(1, browser_client()->GetAndClearBrowsingInstanceDeleteCount());
+}
+
 }  // namespace content
diff --git a/content/child/child_gpu_memory_buffer_manager.cc b/content/child/child_gpu_memory_buffer_manager.cc
index d6e41ec..2986b622 100644
--- a/content/child/child_gpu_memory_buffer_manager.cc
+++ b/content/child/child_gpu_memory_buffer_manager.cc
@@ -34,7 +34,9 @@
 scoped_ptr<gfx::GpuMemoryBuffer>
 ChildGpuMemoryBufferManager::AllocateGpuMemoryBuffer(const gfx::Size& size,
                                                      gfx::BufferFormat format,
-                                                     gfx::BufferUsage usage) {
+                                                     gfx::BufferUsage usage,
+                                                     int32_t surface_id) {
+  DCHECK_EQ(0, surface_id);
   TRACE_EVENT2("renderer",
                "ChildGpuMemoryBufferManager::AllocateGpuMemoryBuffer",
                "width",
diff --git a/content/child/child_gpu_memory_buffer_manager.h b/content/child/child_gpu_memory_buffer_manager.h
index d8ad35af..3b6a456 100644
--- a/content/child/child_gpu_memory_buffer_manager.h
+++ b/content/child/child_gpu_memory_buffer_manager.h
@@ -20,7 +20,8 @@
   scoped_ptr<gfx::GpuMemoryBuffer> AllocateGpuMemoryBuffer(
       const gfx::Size& size,
       gfx::BufferFormat format,
-      gfx::BufferUsage usage) override;
+      gfx::BufferUsage usage,
+      int32_t surface_id) override;
   scoped_ptr<gfx::GpuMemoryBuffer> CreateGpuMemoryBufferFromHandle(
       const gfx::GpuMemoryBufferHandle& handle,
       const gfx::Size& size,
diff --git a/content/child/child_process.h b/content/child/child_process.h
index 3b8c23b..30e9dbf8 100644
--- a/content/child/child_process.h
+++ b/content/child/child_process.h
@@ -62,6 +62,9 @@
   // itself down when the ref count reaches 0.
   // For example, in the renderer process, generally each tab managed by this
   // process will hold a reference to the process, and release when closed.
+  // However for renderer processes specifically, there is also fast shutdown
+  // code path initiated by the browser process. The process refcount does
+  // not influence fast shutdown. See blink::Platform::suddenTerminationChanged.
   void AddRefProcess();
   void ReleaseProcess();
 
diff --git a/content/child/child_thread_impl_browsertest.cc b/content/child/child_thread_impl_browsertest.cc
index ee47fb2b..278dfe5e 100644
--- a/content/child/child_thread_impl_browsertest.cc
+++ b/content/child/child_thread_impl_browsertest.cc
@@ -158,7 +158,8 @@
 
   scoped_ptr<gfx::GpuMemoryBuffer> buffer =
       child_gpu_memory_buffer_manager()->AllocateGpuMemoryBuffer(
-          buffer_size, format, gfx::BufferUsage::GPU_READ_CPU_READ_WRITE);
+          buffer_size, format, gfx::BufferUsage::GPU_READ_CPU_READ_WRITE,
+          0 /* surface_id */);
   ASSERT_TRUE(buffer);
   EXPECT_EQ(format, buffer->GetFormat());
 
diff --git a/content/child/service_worker/service_worker_dispatcher.h b/content/child/service_worker/service_worker_dispatcher.h
index f84f847..f83a820 100644
--- a/content/child/service_worker/service_worker_dispatcher.h
+++ b/content/child/service_worker/service_worker_dispatcher.h
@@ -13,6 +13,7 @@
 #include "base/id_map.h"
 #include "base/macros.h"
 #include "base/memory/ref_counted.h"
+#include "base/memory/scoped_ptr.h"
 #include "base/strings/string16.h"
 #include "content/public/child/worker_thread.h"
 #include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerError.h"
diff --git a/content/child/service_worker/web_service_worker_impl.h b/content/child/service_worker/web_service_worker_impl.h
index 5bcf9d3e..48a3237 100644
--- a/content/child/service_worker/web_service_worker_impl.h
+++ b/content/child/service_worker/web_service_worker_impl.h
@@ -10,6 +10,7 @@
 #include "base/compiler_specific.h"
 #include "base/macros.h"
 #include "base/memory/ref_counted.h"
+#include "base/memory/scoped_ptr.h"
 #include "base/strings/string16.h"
 #include "content/common/content_export.h"
 #include "third_party/WebKit/public/platform/WebMessagePortChannel.h"
diff --git a/content/child/service_worker/web_service_worker_registration_impl.h b/content/child/service_worker/web_service_worker_registration_impl.h
index 41da2774..19229cc 100644
--- a/content/child/service_worker/web_service_worker_registration_impl.h
+++ b/content/child/service_worker/web_service_worker_registration_impl.h
@@ -12,6 +12,7 @@
 #include "base/compiler_specific.h"
 #include "base/macros.h"
 #include "base/memory/ref_counted.h"
+#include "base/memory/scoped_ptr.h"
 #include "content/common/content_export.h"
 #include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerRegistration.h"
 
diff --git a/content/common/gpu/media/gpu_video_encode_accelerator.cc b/content/common/gpu/media/gpu_video_encode_accelerator.cc
index 996611f..0e6d2205 100644
--- a/content/common/gpu/media/gpu_video_encode_accelerator.cc
+++ b/content/common/gpu/media/gpu_video_encode_accelerator.cc
@@ -14,7 +14,6 @@
 #include "content/common/gpu/gpu_channel.h"
 #include "content/common/gpu/gpu_channel_manager.h"
 #include "content/common/gpu/media/gpu_video_accelerator_util.h"
-#include "gpu/ipc/client/gpu_memory_buffer_impl.h"
 #include "ipc/ipc_message_macros.h"
 #include "media/base/bind_to_current_loop.h"
 #include "media/base/limits.h"
@@ -36,14 +35,6 @@
 
 namespace content {
 
-namespace {
-
-// Allocation and destruction of buffer are done on the Browser process, so we
-// don't need to handle synchronization here.
-void DestroyGpuMemoryBuffer(const gpu::SyncToken& sync_token) {}
-
-} // namespace
-
 static bool MakeDecoderContextCurrent(
     const base::WeakPtr<GpuCommandBufferStub> stub) {
   if (!stub) {
@@ -334,79 +325,8 @@
            << params.frame_id << ", size=" << params.size.ToString()
            << ", force_keyframe=" << params.force_keyframe << ", handle type="
            << params.gpu_memory_buffer_handles[0].type;
-  DCHECK_EQ(media::PIXEL_FORMAT_I420, input_format_);
-  DCHECK_EQ(media::VideoFrame::NumPlanes(input_format_),
-            params.gpu_memory_buffer_handles.size());
-
-  bool map_result = true;
-  uint8_t* data[media::VideoFrame::kMaxPlanes];
-  int32_t strides[media::VideoFrame::kMaxPlanes];
-  ScopedVector<gfx::GpuMemoryBuffer> buffers;
-  const auto& handles = params.gpu_memory_buffer_handles;
-  for (size_t i = 0; i < handles.size(); ++i) {
-    const size_t width =
-        media::VideoFrame::Columns(i, input_format_, params.size.width());
-    const size_t height =
-        media::VideoFrame::Rows(i, input_format_, params.size.height());
-    scoped_ptr<gfx::GpuMemoryBuffer> buffer =
-        gpu::GpuMemoryBufferImpl::CreateFromHandle(
-            handles[i], gfx::Size(width, height), gfx::BufferFormat::R_8,
-            gfx::BufferUsage::GPU_READ_CPU_READ_WRITE,
-            media::BindToCurrentLoop(base::Bind(&DestroyGpuMemoryBuffer)));
-
-    // TODO(emircan): Refactor such that each frame is mapped once.
-    // See http://crbug/536938.
-    if (!buffer.get() || !buffer->Map()) {
-      map_result = false;
-      continue;
-    }
-
-    data[i] = reinterpret_cast<uint8_t*>(buffer->memory(0));
-    strides[i] = buffer->stride(0);
-    buffers.push_back(buffer.release());
-  }
-
-  if (!map_result) {
-    DLOG(ERROR) << "GpuVideoEncodeAccelerator::OnEncode2(): "
-                << "failed to map buffers";
-    NotifyError(media::VideoEncodeAccelerator::kPlatformFailureError);
-    return;
-  }
-
-  if (!encoder_)
-    return;
-
-  if (params.frame_id < 0) {
-    DLOG(ERROR) << "GpuVideoEncodeAccelerator::OnEncode2(): invalid frame_id="
-                << params.frame_id;
-    NotifyError(media::VideoEncodeAccelerator::kPlatformFailureError);
-    return;
-  }
-
-  scoped_refptr<media::VideoFrame> frame =
-      media::VideoFrame::WrapExternalYuvData(
-          input_format_,
-          input_coded_size_,
-          gfx::Rect(input_visible_size_),
-          input_visible_size_,
-          strides[media::VideoFrame::kYPlane],
-          strides[media::VideoFrame::kUPlane],
-          strides[media::VideoFrame::kVPlane],
-          data[media::VideoFrame::kYPlane],
-          data[media::VideoFrame::kUPlane],
-          data[media::VideoFrame::kVPlane],
-          params.timestamp);
-  if (!frame.get()) {
-    DLOG(ERROR) << "GpuVideoEncodeAccelerator::OnEncode2(): "
-                << "could not create a frame";
-    NotifyError(media::VideoEncodeAccelerator::kPlatformFailureError);
-    return;
-  }
-  frame->AddDestructionObserver(media::BindToCurrentLoop(
-      base::Bind(&GpuVideoEncodeAccelerator::EncodeFrameFinished2,
-                 weak_this_factory_.GetWeakPtr(), params.frame_id,
-                 base::Passed(&buffers))));
-  encoder_->Encode(frame, params.force_keyframe);
+  // Encoding GpuMemoryBuffer backed frames is not supported.
+  NOTREACHED();
 }
 
 void GpuVideoEncodeAccelerator::OnUseOutputBitstreamBuffer(
@@ -458,17 +378,6 @@
   // Just let |shm| fall out of scope.
 }
 
-void GpuVideoEncodeAccelerator::EncodeFrameFinished2(
-    int32_t frame_id,
-    ScopedVector<gfx::GpuMemoryBuffer> buffers) {
-  // TODO(emircan): Consider calling Unmap() in dtor.
-  for (const auto& buffer : buffers)
-    buffer->Unmap();
-  Send(new AcceleratedVideoEncoderHostMsg_NotifyInputDone(host_route_id_,
-                                                          frame_id));
-  // Just let |buffers| fall out of scope.
-}
-
 void GpuVideoEncodeAccelerator::Send(IPC::Message* message) {
   stub_->channel()->Send(message);
 }
diff --git a/content/common/gpu/media/gpu_video_encode_accelerator.h b/content/common/gpu/media/gpu_video_encode_accelerator.h
index e09cb18..dff1d9c5 100644
--- a/content/common/gpu/media/gpu_video_encode_accelerator.h
+++ b/content/common/gpu/media/gpu_video_encode_accelerator.h
@@ -104,8 +104,6 @@
 
   void EncodeFrameFinished(int32_t frame_id,
                            scoped_ptr<base::SharedMemory> shm);
-  void EncodeFrameFinished2(int32_t frame_id,
-                            ScopedVector<gfx::GpuMemoryBuffer> buffers);
   void Send(IPC::Message* message);
 
   // Route ID to communicate with the host.
diff --git a/content/common/sandbox_util.cc b/content/common/sandbox_util.cc
index eea8486..75b3977f 100644
--- a/content/common/sandbox_util.cc
+++ b/content/common/sandbox_util.cc
@@ -6,6 +6,7 @@
 
 #include "build/build_config.h"
 #include "content/public/common/sandbox_init.h"
+#include "ipc/ipc_platform_file.h"
 
 #if defined(OS_POSIX)
 #include <unistd.h>
@@ -17,33 +18,7 @@
     base::PlatformFile handle,
     base::ProcessId target_process_id,
     bool should_close_source) {
-  IPC::PlatformFileForTransit out_handle;
-#if defined(OS_WIN)
-  DWORD options = DUPLICATE_SAME_ACCESS;
-  if (should_close_source)
-    options |= DUPLICATE_CLOSE_SOURCE;
-  HANDLE raw_handle = INVALID_HANDLE_VALUE;
-  if (content::BrokerDuplicateHandle(handle, target_process_id, &raw_handle, 0,
-                                     options)) {
-    out_handle = IPC::PlatformFileForTransit(raw_handle, target_process_id);
-  } else {
-    out_handle = IPC::InvalidPlatformFileForTransit();
-  }
-#elif defined(OS_POSIX)
-  // If asked to close the source, we can simply re-use the source fd instead of
-  // dup()ing and close()ing.
-  // When we're not closing the source, we need to duplicate the handle and take
-  // ownership of that. The reason is that this function is often used to
-  // generate IPC messages, and the handle must remain valid until it's sent to
-  // the other process from the I/O thread. Without the dup, calling code might
-  // close the source handle before the message is sent, creating a race
-  // condition.
-  int fd = should_close_source ? handle : ::dup(handle);
-  out_handle = base::FileDescriptor(fd, true);
-#else
-  #error Not implemented.
-#endif
-  return out_handle;
+  return IPC::GetPlatformFileForTransit(handle, should_close_source);
 }
 
 }  // namespace content
diff --git a/content/content_browser.gypi b/content/content_browser.gypi
index 5025d03..bd50f0a 100644
--- a/content/content_browser.gypi
+++ b/content/content_browser.gypi
@@ -97,6 +97,7 @@
   'variables': {
     'public_browser_sources': [
       'public/browser/access_token_store.h',
+      'public/browser/android/service_registry_android.h',
       'public/browser/android/browser_media_player_manager_register.cc',
       'public/browser/android/browser_media_player_manager_register.h',
       'public/browser/android/compositor.h',
@@ -405,6 +406,8 @@
       'browser/android/devtools_auth.cc',
       'browser/android/in_process_surface_texture_manager.cc',
       'browser/android/in_process_surface_texture_manager.h',
+      'browser/android/service_registry_android_impl.cc',
+      'browser/android/service_registry_android_impl.h',
       'browser/android/url_request_content_job.cc',
       'browser/android/url_request_content_job.h',
       'browser/appcache/appcache.cc',
@@ -1127,8 +1130,6 @@
       'browser/mojo/mojo_shell_context.h',
       'browser/mojo/service_registrar_android.cc',
       'browser/mojo/service_registrar_android.h',
-      'browser/mojo/service_registry_android.cc',
-      'browser/mojo/service_registry_android.h',
       'browser/net/browser_online_state_observer.cc',
       'browser/net/browser_online_state_observer.h',
       'browser/net/network_errors_listing_ui.cc',
diff --git a/content/public/android/java/src/org/chromium/content/browser/ServiceRegistry.java b/content/public/android/java/src/org/chromium/content/browser/ServiceRegistry.java
index 21a7aac..b81267b 100644
--- a/content/public/android/java/src/org/chromium/content/browser/ServiceRegistry.java
+++ b/content/public/android/java/src/org/chromium/content/browser/ServiceRegistry.java
@@ -19,11 +19,20 @@
 @JNINamespace("content")
 public class ServiceRegistry {
 
-    interface ImplementationFactory<I extends Interface> {
+    /**
+     * The interface that a factory should implement.
+     */
+    public interface ImplementationFactory<I extends Interface> {
         I createImpl();
     }
 
-    <I extends Interface, P extends Proxy> void addService(
+    /**
+     * Adds a service factory.
+     *
+     * @param manager The interface manager.
+     * @param factory The service factory.
+     */
+    public <I extends Interface, P extends Proxy> void addService(
             Interface.Manager<I, P> manager, ImplementationFactory<I> factory) {
         nativeAddService(mNativeServiceRegistryAndroid, manager, factory, manager.getName());
     }
diff --git a/content/public/browser/android/service_registry_android.h b/content/public/browser/android/service_registry_android.h
new file mode 100644
index 0000000..e134b431
--- /dev/null
+++ b/content/public/browser/android/service_registry_android.h
@@ -0,0 +1,51 @@
+// Copyright 2016 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 CONTENT_PUBLIC_BROWSER_ANDROID_SERVICE_REGISTRY_ANDROID_H_
+#define CONTENT_PUBLIC_BROWSER_ANDROID_SERVICE_REGISTRY_ANDROID_H_
+
+#include <jni.h>
+#include <memory>
+
+#include "base/android/scoped_java_ref.h"
+#include "content/common/content_export.h"
+
+namespace content {
+
+class ServiceRegistry;
+
+// Android wrapper over ServiceRegistry, allowing the browser services in Java
+// to register with ServiceRegistry.java (and abstracting away the JNI calls).
+class CONTENT_EXPORT ServiceRegistryAndroid {
+ public:
+  virtual ~ServiceRegistryAndroid() {}
+
+  // The |registry| parameter must outlive |ServiceRegistryAndroid|.
+  static std::unique_ptr<ServiceRegistryAndroid> Create(
+      ServiceRegistry* registry);
+
+  // Called from Java.
+  virtual void AddService(
+      JNIEnv* env,
+      const base::android::JavaParamRef<jobject>& j_service_registry,
+      const base::android::JavaParamRef<jobject>& j_manager,
+      const base::android::JavaParamRef<jobject>& j_factory,
+      const base::android::JavaParamRef<jstring>& j_name) = 0;
+  virtual void RemoveService(
+      JNIEnv* env,
+      const base::android::JavaParamRef<jobject>& j_service_registry,
+      const base::android::JavaParamRef<jstring>& j_name) = 0;
+  virtual void ConnectToRemoteService(
+      JNIEnv* env,
+      const base::android::JavaParamRef<jobject>& j_service_registry,
+      const base::android::JavaParamRef<jstring>& j_name,
+      jint handle) = 0;
+
+  // Accessor to the Java object.
+  virtual const base::android::ScopedJavaGlobalRef<jobject>& GetObj() = 0;
+};
+
+}  // namespace content
+
+#endif  // CONTENT_PUBLIC_BROWSER_ANDROID_SERVICE_REGISTRY_ANDROID_H_
diff --git a/content/public/browser/content_browser_client.cc b/content/public/browser/content_browser_client.cc
index 8c89653..3279d61dc 100644
--- a/content/public/browser/content_browser_client.cc
+++ b/content/public/browser/content_browser_client.cc
@@ -225,6 +225,10 @@
   return AllowWebBluetoothResult::ALLOW;
 }
 
+std::string ContentBrowserClient::GetWebBluetoothBlacklist() {
+  return std::string();
+}
+
 QuotaPermissionContext* ContentBrowserClient::CreateQuotaPermissionContext() {
   return nullptr;
 }
diff --git a/content/public/browser/content_browser_client.h b/content/public/browser/content_browser_client.h
index 5e25bcb..8954d1da 100644
--- a/content/public/browser/content_browser_client.h
+++ b/content/public/browser/content_browser_client.h
@@ -415,6 +415,21 @@
       const url::Origin& requesting_origin,
       const url::Origin& embedding_origin);
 
+  // Returns a blacklist of UUIDs that have restrictions when accessed
+  // via Web Bluetooth. Parsed by BluetoothBlacklist::Add().
+  //
+  // The blacklist string must be a comma-separated list of UUID:exclusion
+  // pairs. The pairs may be separated by whitespace. Pair components are
+  // colon-separated and must not have whitespace around the colon.
+  //
+  // UUIDs are a string that BluetoothUUID can parse (See BluetoothUUID
+  // constructor comment). Exclusion values are a single lower case character
+  // string "e", "r", or "w" for EXCLUDE, EXCLUDE_READS, or EXCLUDE_WRITES.
+  //
+  // Example:
+  // "1812:e, 00001800-0000-1000-8000-00805f9b34fb:w, ignored:1, alsoignored."
+  virtual std::string GetWebBluetoothBlacklist();
+
   // Allow the embedder to override the request context based on the URL for
   // certain operations, like cookie access. Returns nullptr to indicate the
   // regular request context should be used.
diff --git a/content/public/common/content_switches.cc b/content/public/common/content_switches.cc
index 64d4e33..621fab7 100644
--- a/content/public/common/content_switches.cc
+++ b/content/public/common/content_switches.cc
@@ -771,14 +771,6 @@
 const char kStatsCollectionController[] =
     "enable-stats-collection-bindings";
 
-// Upscale defaults to "good".
-const char kTabCaptureDownscaleQuality[]    = "tab-capture-downscale-quality";
-
-// Scaling quality for capturing tab. Should be one of "fast", "good" or "best".
-// One flag for upscaling, one for downscaling.
-// Upscale defaults to "best".
-const char kTabCaptureUpscaleQuality[]      = "tab-capture-upscale-quality";
-
 // Allows for forcing socket connections to http/https to use fixed ports.
 const char kTestingFixedHttpPort[]          = "testing-fixed-http-port";
 const char kTestingFixedHttpsPort[]         = "testing-fixed-https-port";
diff --git a/content/public/common/content_switches.h b/content/public/common/content_switches.h
index af9e2769..407f2cb2 100644
--- a/content/public/common/content_switches.h
+++ b/content/public/common/content_switches.h
@@ -213,8 +213,6 @@
 extern const char kSkipReencodingOnSKPCapture[];
 CONTENT_EXPORT extern const char kStartFullscreen[];
 CONTENT_EXPORT extern const char kStatsCollectionController[];
-CONTENT_EXPORT extern const char kTabCaptureDownscaleQuality[];
-CONTENT_EXPORT extern const char kTabCaptureUpscaleQuality[];
 CONTENT_EXPORT extern const char kTestingFixedHttpPort[];
 CONTENT_EXPORT extern const char kTestingFixedHttpsPort[];
 CONTENT_EXPORT extern const char kTestType[];
diff --git a/content/renderer/media/android/renderer_media_session_manager.h b/content/renderer/media/android/renderer_media_session_manager.h
index 5c5a2f2..850406c 100644
--- a/content/renderer/media/android/renderer_media_session_manager.h
+++ b/content/renderer/media/android/renderer_media_session_manager.h
@@ -9,6 +9,7 @@
 
 #include "base/id_map.h"
 #include "base/macros.h"
+#include "base/memory/scoped_ptr.h"
 #include "content/common/content_export.h"
 #include "content/public/renderer/render_frame_observer.h"
 #include "third_party/WebKit/public/platform/modules/mediasession/WebMediaSession.h"
diff --git a/content/renderer/media/renderer_gpu_video_accelerator_factories.cc b/content/renderer/media/renderer_gpu_video_accelerator_factories.cc
index 3f77685..5976a5dd 100644
--- a/content/renderer/media/renderer_gpu_video_accelerator_factories.cc
+++ b/content/renderer/media/renderer_gpu_video_accelerator_factories.cc
@@ -220,7 +220,8 @@
     gfx::BufferFormat format,
     gfx::BufferUsage usage) {
   scoped_ptr<gfx::GpuMemoryBuffer> buffer =
-      gpu_memory_buffer_manager_->AllocateGpuMemoryBuffer(size, format, usage);
+      gpu_memory_buffer_manager_->AllocateGpuMemoryBuffer(size, format, usage,
+                                                          0 /* surface_id */);
   return buffer;
 }
 bool RendererGpuVideoAcceleratorFactories::
diff --git a/content/renderer/render_view_impl.cc b/content/renderer/render_view_impl.cc
index 88b8ed4..76b0fb6 100644
--- a/content/renderer/render_view_impl.cc
+++ b/content/renderer/render_view_impl.cc
@@ -1486,12 +1486,6 @@
     blink::WebView* web_view,
     CompositorDependencies* compositor_deps) {
   ApplyWebPreferences(prefs, web_view);
-#if defined(OS_MACOSX)
-  DCHECK(compositor_deps);
-  bool is_elastic_overscroll_enabled =
-      compositor_deps->IsElasticOverscrollEnabled();
-  web_view->settings()->setReportWheelOverscroll(is_elastic_overscroll_enabled);
-#endif
 }
 
 void RenderViewImpl::OnForceRedraw(int id) {
diff --git a/content/renderer/render_widget.cc b/content/renderer/render_widget.cc
index ecf8ae40..18461075 100644
--- a/content/renderer/render_widget.cc
+++ b/content/renderer/render_widget.cc
@@ -2019,6 +2019,13 @@
     const blink::WebFloatSize& accumulatedRootOverScroll,
     const blink::WebFloatPoint& position,
     const blink::WebFloatSize& velocity) {
+#if defined(OS_MACOSX)
+  // On OSX the user can disable the elastic overscroll effect. If that's the
+  // case, don't forward the overscroll notification.
+  DCHECK(compositor_deps());
+  if (!compositor_deps()->IsElasticOverscrollEnabled())
+    return;
+#endif
   input_handler_->DidOverscrollFromBlink(unusedDelta, accumulatedRootOverScroll,
                                          position, velocity);
 }
diff --git a/content/shell/browser/shell_mojo_test_utils_android.cc b/content/shell/browser/shell_mojo_test_utils_android.cc
index 807cb57..372b827 100644
--- a/content/shell/browser/shell_mojo_test_utils_android.cc
+++ b/content/shell/browser/shell_mojo_test_utils_android.cc
@@ -9,8 +9,8 @@
 #include "base/memory/scoped_vector.h"
 #include "base/message_loop/message_loop.h"
 #include "base/run_loop.h"
-#include "content/browser/mojo/service_registry_android.h"
 #include "content/common/mojo/service_registry_impl.h"
+#include "content/public/browser/android/service_registry_android.h"
 #include "jni/ShellMojoTestUtils_jni.h"
 
 namespace {
@@ -57,10 +57,10 @@
   registry_a->BindRemoteServiceProvider(std::move(exposed_services_b));
 
   content::ServiceRegistryAndroid* wrapper_a =
-      new ServiceRegistryAndroid(registry_a);
+      ServiceRegistryAndroid::Create(registry_a).release();
   test_environment->wrappers.push_back(wrapper_a);
   content::ServiceRegistryAndroid* wrapper_b =
-      new ServiceRegistryAndroid(registry_b);
+      ServiceRegistryAndroid::Create(registry_b).release();
   test_environment->wrappers.push_back(wrapper_b);
 
   return Java_ShellMojoTestUtils_makePair(env, wrapper_a->GetObj().obj(),
diff --git a/content/test/data/service_worker/fetch_cross_origin.html b/content/test/data/service_worker/fetch_cross_origin.html
new file mode 100644
index 0000000..e0f9ae83
--- /dev/null
+++ b/content/test/data/service_worker/fetch_cross_origin.html
@@ -0,0 +1,17 @@
+<!DOCTYPE html>
+<html>
+<head>
+<title>INITIAL</title>
+<script>
+var queryString = location.search;
+
+if (queryString && queryString.charAt(0) === '?') {
+  // Fetches the URL provided in query string with a custom header.
+  fetch(queryString.substring(1), {headers: {'X-Custom-Header': 'foo'}})
+    .then(data => data.text())
+    .then(text => document.title = text)
+    .catch(() => document.title = 'FAIL');
+}
+</script>
+</head>
+</html>
diff --git a/content/test/data/service_worker/fetch_event_respond_with_fetch.js b/content/test/data/service_worker/fetch_event_respond_with_fetch.js
new file mode 100644
index 0000000..df76d0a0
--- /dev/null
+++ b/content/test/data/service_worker/fetch_event_respond_with_fetch.js
@@ -0,0 +1,7 @@
+// Copyright 2016 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.
+
+this.onfetch = function(event) {
+  event.respondWith(fetch(event.request));
+};
diff --git a/content/test/fake_compositor_dependencies.cc b/content/test/fake_compositor_dependencies.cc
index ea6ca2f7..a92e449 100644
--- a/content/test/fake_compositor_dependencies.cc
+++ b/content/test/fake_compositor_dependencies.cc
@@ -53,7 +53,7 @@
 }
 
 bool FakeCompositorDependencies::IsElasticOverscrollEnabled() {
-  return false;
+  return true;
 }
 std::vector<unsigned> FakeCompositorDependencies::GetImageTextureTargets() {
   return std::vector<unsigned>(static_cast<size_t>(gfx::BufferFormat::LAST) + 1,
diff --git a/courgette/image_utils.h b/courgette/image_utils.h
index aa539b6..643b9fb2 100644
--- a/courgette/image_utils.h
+++ b/courgette/image_utils.h
@@ -8,6 +8,9 @@
 #include <stddef.h>
 #include <stdint.h>
 
+#include <iterator>
+#include <vector>
+
 // COURGETTE_HISTOGRAM_TARGETS prints out a histogram of how frequently
 // different target addresses are referenced. Purely for debugging.
 #define COURGETTE_HISTOGRAM_TARGETS 0
@@ -90,6 +93,53 @@
   int32_t count_ = 0;
 };
 
+// An interface for sequential visit of RVAs.
+// Use case: Translating from RVA locations to RVA targets is platform-specific,
+// and works differently for abs32 vs. rel32. A function that sequentually
+// visits RVA targets only requires an RvaVisitor. The caller can provide an
+// implementation that stores a fixed list of RVA locations, and translates each
+// to the matching RVA target on demand without extra storage.
+class RvaVisitor {
+ public:
+  // Returns the number of remaining RVAs to visit.
+  virtual size_t Remaining() const = 0;
+
+  // Returns the current RVA.
+  virtual RVA Get() const = 0;
+
+  // Advances to the next RVA.
+  virtual void Next() = 0;
+};
+
+// RvaVisitor whose data are backed by std::vector<T>. Translating from T to RVA
+// is should be implemented in Get().
+template <typename T>
+class VectorRvaVisitor : public RvaVisitor {
+ public:
+  // Assumes |v| does not change for the lifetime of this instance.
+  explicit VectorRvaVisitor(const std::vector<T>& v)
+      : it_(v.begin()), end_(v.end()) {}
+
+  // RvaVisitor interfaces.
+  size_t Remaining() const override { return std::distance(it_, end_); }
+  virtual RVA Get() const override = 0;
+  void Next() override { ++it_; }
+
+ protected:
+  typename std::vector<T>::const_iterator it_;
+  typename std::vector<T>::const_iterator end_;
+};
+
+// RvaVisitor that simply stores a list of RVAs for traversal. For testing.
+class TrivialRvaVisitor : public VectorRvaVisitor<RVA> {
+ public:
+  explicit TrivialRvaVisitor(const std::vector<RVA>& rvas)
+      : VectorRvaVisitor<RVA>(rvas) {}
+
+  // VectorRvaVisitor<RVA> interfaces.
+  RVA Get() const override { return *it_; }
+};
+
 // These helper functions avoid the need for casts in the main code.
 inline uint16_t ReadU16(const uint8_t* address, size_t offset) {
   return *reinterpret_cast<const uint16_t*>(address + offset);
diff --git a/courgette/label_manager.cc b/courgette/label_manager.cc
index bd568b0f..a109d8b 100644
--- a/courgette/label_manager.cc
+++ b/courgette/label_manager.cc
@@ -16,38 +16,11 @@
 
 namespace courgette {
 
-LabelManager::LabelManager() {}
-
-LabelManager::~LabelManager() {}
-
-// static
-int LabelManager::GetIndexBound(const LabelVector& labels) {
-  int max_index = -1;
-  for (const Label& label : labels) {
-    if (label.index_ != Label::kNoIndex)
-      max_index = std::max(max_index, label.index_);
-  }
-  return max_index + 1;
-}
-
-// static
-int LabelManager::GetIndexBound(const RVAToLabel& labels_map) {
-  int max_index = -1;
-  for (const auto& rva_and_label : labels_map) {
-    const Label& label = *rva_and_label.second;
-    if (label.index_ != Label::kNoIndex)
-      max_index = std::max(max_index, label.index_);
-  }
-  return max_index + 1;
-}
-
-LabelManagerImpl::RvaVisitor::~RvaVisitor() {}
-
-LabelManagerImpl::SimpleIndexAssigner::SimpleIndexAssigner(LabelVector* labels)
+LabelManager::SimpleIndexAssigner::SimpleIndexAssigner(LabelVector* labels)
     : labels_(labels) {
   // Initialize |num_index_| and |available_|.
   num_index_ = std::max(base::checked_cast<int>(labels_->size()),
-                        LabelManager::GetIndexBound(*labels_));
+                        GetLabelIndexBound(*labels_));
   available_.resize(num_index_, true);
   size_t used = 0;
   for (const Label& label : *labels_) {
@@ -59,9 +32,9 @@
   VLOG(1) << used << " of " << labels_->size() << " labels pre-assigned.";
 }
 
-LabelManagerImpl::SimpleIndexAssigner::~SimpleIndexAssigner() {}
+LabelManager::SimpleIndexAssigner::~SimpleIndexAssigner() {}
 
-void LabelManagerImpl::SimpleIndexAssigner::DoForwardFill() {
+void LabelManager::SimpleIndexAssigner::DoForwardFill() {
   size_t count = 0;
   // Inside the loop, if |prev_index| == |kNoIndex| then we try to assign 0.
   // This allows 0 (if unused) to be assigned in middle of |labels_|.
@@ -80,7 +53,7 @@
   VLOG(1) << "  fill forward " << count;
 }
 
-void LabelManagerImpl::SimpleIndexAssigner::DoBackwardFill() {
+void LabelManager::SimpleIndexAssigner::DoBackwardFill() {
   size_t count = 0;
   // This is asymmetric from DoForwardFill(), to preserve old behavior.
   // Inside the loop, if |prev_index| == |kNoIndex| then we skip assignment.
@@ -102,7 +75,7 @@
   VLOG(1) << "  fill backward " << count;
 }
 
-void LabelManagerImpl::SimpleIndexAssigner::DoInFill() {
+void LabelManager::SimpleIndexAssigner::DoInFill() {
   size_t count = 0;
   int index = 0;
   for (Label& label : *labels_) {
@@ -118,9 +91,71 @@
   VLOG(1) << "  infill " << count;
 }
 
-LabelManagerImpl::LabelManagerImpl() {}
+LabelManager::LabelManager() {}
 
-LabelManagerImpl::~LabelManagerImpl() {}
+LabelManager::~LabelManager() {}
+
+// static
+int LabelManager::GetIndexBound(const RVAToLabel& labels_map) {
+  int max_index = -1;
+  for (const auto& rva_and_label : labels_map) {
+    const Label& label = *rva_and_label.second;
+    if (label.index_ != Label::kNoIndex)
+      max_index = std::max(max_index, label.index_);
+  }
+  return max_index + 1;
+}
+
+// static
+int LabelManager::GetLabelIndexBound(const LabelVector& labels) {
+  int max_index = -1;
+  for (const Label& label : labels) {
+    if (label.index_ != Label::kNoIndex)
+      max_index = std::max(max_index, label.index_);
+  }
+  return max_index + 1;
+}
+
+// Uses binary search to find |rva|.
+Label* LabelManager::Find(RVA rva) {
+  auto it = std::lower_bound(
+      labels_.begin(), labels_.end(), Label(rva),
+      [](const Label& l1, const Label& l2) { return l1.rva_ < l2.rva_; });
+  return it == labels_.end() || it->rva_ != rva ? nullptr : &(*it);
+}
+
+void LabelManager::RemoveUnderusedLabels(int32_t count_threshold) {
+  if (count_threshold <= 0)
+    return;
+  labels_.erase(std::remove_if(labels_.begin(), labels_.end(),
+                               [count_threshold](const Label& label) {
+                                 return label.count_ < count_threshold;
+                               }),
+                labels_.end());
+  // Not shrinking |labels_|, since this may cause reallocation.
+}
+
+void LabelManager::UnassignIndexes() {
+  for (Label& label : labels_)
+    label.index_ = Label::kNoIndex;
+}
+
+void LabelManager::DefaultAssignIndexes() {
+  int cur_index = 0;
+  for (Label& label : labels_) {
+    CHECK_EQ(Label::kNoIndex, label.index_);
+    label.index_ = cur_index++;
+  }
+}
+
+void LabelManager::AssignRemainingIndexes() {
+  // This adds some memory overhead, about 1 bit per Label (more if indexes >=
+  // |labels_.size()| get used).
+  SimpleIndexAssigner assigner(&labels_);
+  assigner.DoForwardFill();
+  assigner.DoBackwardFill();
+  assigner.DoInFill();
+}
 
 // We wish to minimize peak memory usage here. Analysis: Let
 //   m = number of (RVA) elements in |rva_visitor|,
@@ -132,7 +167,7 @@
 // For our typical usage (i.e. Chrome) we see m = ~4n, so we use 16 * n bytes of
 // extra contiguous memory during computation. Assuming memory fragmentation
 // would not be an issue, this is much better than using std::map.
-void LabelManagerImpl::Read(RvaVisitor* rva_visitor) {
+void LabelManager::Read(RvaVisitor* rva_visitor) {
   // Write all values in |rva_visitor| to |rvas|.
   size_t num_rva = rva_visitor->Remaining();
   std::vector<RVA> rvas(num_rva);
@@ -158,53 +193,4 @@
   }
 }
 
-size_t LabelManagerImpl::Size() const {
-  return labels_.size();
-}
-
-// Uses binary search to find |rva|.
-Label* LabelManagerImpl::Find(RVA rva) {
-  auto it = std::lower_bound(
-      labels_.begin(), labels_.end(), Label(rva),
-      [](const Label& l1, const Label& l2) { return l1.rva_ < l2.rva_; });
-  return it == labels_.end() || it->rva_ != rva ? nullptr : &(*it);
-}
-
-void LabelManagerImpl::RemoveUnderusedLabels(int32_t count_threshold) {
-  if (count_threshold <= 0)
-    return;
-  labels_.erase(std::remove_if(labels_.begin(), labels_.end(),
-                               [count_threshold](const Label& label) {
-                                 return label.count_ < count_threshold;
-                               }),
-                labels_.end());
-  // Not shrinking |labels_|, since this may cause reallocation.
-}
-
-void LabelManagerImpl::UnassignIndexes() {
-  for (Label& label : labels_)
-    label.index_ = Label::kNoIndex;
-}
-
-void LabelManagerImpl::DefaultAssignIndexes() {
-  int cur_index = 0;
-  for (Label& label : labels_) {
-    CHECK_EQ(Label::kNoIndex, label.index_);
-    label.index_ = cur_index++;
-  }
-}
-
-void LabelManagerImpl::AssignRemainingIndexes() {
-  // This adds some memory overhead, about 1 bit per Label (more if indexes >=
-  // |labels_.size()| get used).
-  SimpleIndexAssigner assigner(&labels_);
-  assigner.DoForwardFill();
-  assigner.DoBackwardFill();
-  assigner.DoInFill();
-}
-
-void LabelManagerImpl::SetLabels(const LabelVector& labels) {
-  labels_ = labels;
-}
-
 }  // namespace courgette
diff --git a/courgette/label_manager.h b/courgette/label_manager.h
index 72783cf..d60a274 100644
--- a/courgette/label_manager.h
+++ b/courgette/label_manager.h
@@ -20,66 +20,11 @@
 using LabelVector = std::vector<Label>;
 using RVAToLabel = std::map<RVA, Label*>;
 
-// A container to store and manage Label instances.
+// A container to store and manage Label instances, dedicated to reducing peak
+// memory usage. To this end we preallocate Label instances in bulk, and
+// carefully control transient memory usage when initializing Labels.
 class LabelManager {
  public:
-  virtual ~LabelManager();
-
-  // Returns an exclusive upper bound for all existing indexes in |labels|.
-  static int GetIndexBound(const LabelVector& labels);
-
-  // Returns an exclusive upper bound for all existing indexes in |labels_map|.
-  static int GetIndexBound(const RVAToLabel& labels_map);
-
-  // Returns the number of Label instances stored.
-  virtual size_t Size() const = 0;
-
-  // Efficiently searches for a Label that targets |rva|. Returns the pointer to
-  // the stored Label instance if found, or null otherwise. Non-const to support
-  // implementations that allocate-on-read.
-  virtual Label* Find(RVA rva) = 0;
-
-  // Removes Label instances whose |count_| is less than |count_threshold|.
-  virtual void RemoveUnderusedLabels(int32_t count_threshold) = 0;
-
-  // Resets all indexes to an unassigned state.
-  virtual void UnassignIndexes() = 0;
-
-  // Assigns indexes to successive integers from 0, ordered by RVA.
-  virtual void DefaultAssignIndexes() = 0;
-
-  // Assigns indexes to any Label instances that don't have one yet.
-  virtual void AssignRemainingIndexes() = 0;
-
- protected:
-  LabelManager();
-
- private:
-  DISALLOW_COPY_AND_ASSIGN(LabelManager);
-};
-
-// An implementation of LabelManager dedicated to reducing peak memory usage.
-// To this end we preallocate Label instances in bulk, and carefully control
-// transient memory usage when initializing Labels.
-class LabelManagerImpl : public LabelManager {
- public:
-  // An adaptor to sequentially traverse multiple RVAs. This is useful for RVA
-  // translation without extra storage. For example, we might have a stored list
-  // of RVA locations, but we want to traverse the matching RVA targets.
-  class RvaVisitor {
-   public:
-    virtual ~RvaVisitor();
-
-    // Returns the number of remaining RVAs to visit.
-    virtual size_t Remaining() const = 0;
-
-    // Returns the current RVA.
-    virtual RVA Get() const = 0;
-
-    // Advances to the next RVA.
-    virtual void Next() = 0;
-  };
-
   // A helper class to heuristically complete index assignment for a list of
   // Labels that have partially assigned indexes.
   // Goal: An address table compresses best when each index is associated with
@@ -104,7 +49,7 @@
   // distances between successive RVAs.
   class SimpleIndexAssigner {
    public:
-    SimpleIndexAssigner(LabelVector* labels);
+    explicit SimpleIndexAssigner(LabelVector* labels);
     ~SimpleIndexAssigner();
 
     // Scans forward to assign successive indexes to Labels, using existing
@@ -120,7 +65,7 @@
     void DoInFill();
 
    private:
-    // List of Labels to process. Owned by caller.
+    // The target LabelVector, owned by the caller.
     LabelVector* labels_;
 
     // A bound on indexes.
@@ -132,16 +77,35 @@
     DISALLOW_COPY_AND_ASSIGN(SimpleIndexAssigner);
   };
 
-  LabelManagerImpl();
-  ~LabelManagerImpl() override;
+  LabelManager();
+  ~LabelManager();
 
-  // LabelManager interfaces.
-  size_t Size() const override;
-  Label* Find(RVA rva) override;
-  void RemoveUnderusedLabels(int32_t count_threshold) override;
-  void UnassignIndexes() override;
-  void DefaultAssignIndexes() override;
-  void AssignRemainingIndexes() override;
+  // Returns an exclusive upper bound for all existing indexes in |labels_map|.
+  // TODO(huangs): Remove once all callers are gone.
+  static int GetIndexBound(const RVAToLabel& labels_map);
+
+  // Returns an exclusive upper bound for all assigned indexes in |labels|.
+  static int GetLabelIndexBound(const LabelVector& labels);
+
+  // Accessor to stored Label instances.
+  const LabelVector& Labels() const { return labels_; }
+
+  // Efficiently searches for a Label that targets |rva|. Returns the pointer to
+  // the stored Label instance if found, or null otherwise. Non-const to support
+  // implementations that allocate-on-read.
+  Label* Find(RVA rva);
+
+  // Removes Label instances whose |count_| is less than |count_threshold|.
+  void RemoveUnderusedLabels(int32_t count_threshold);
+
+  // Resets all indexes to an unassigned state.
+  void UnassignIndexes();
+
+  // Assigns indexes to successive integers from 0, ordered by RVA.
+  void DefaultAssignIndexes();
+
+  // Assigns indexes to any Label instances that don't have one yet.
+  void AssignRemainingIndexes();
 
   // Populates |labels_| using RVAs from |rva_visitor|. Each distinct RVA from
   // |rva_visitor| yields a Label with |rva_| assigned as the RVA, and |count_|
@@ -149,20 +113,14 @@
   void Read(RvaVisitor* rva_visitor);
 
  protected:
+  FRIEND_TEST_ALL_PREFIXES(LabelManagerTest, TrivialAssign);
+  FRIEND_TEST_ALL_PREFIXES(LabelManagerTest, AssignRemainingIndexes);
+
   // The main list of Label instances, sorted by the |rva_| member.
   LabelVector labels_;
 
  private:
-  FRIEND_TEST_ALL_PREFIXES(LabelManagerTest, TrivialAssign);
-  FRIEND_TEST_ALL_PREFIXES(LabelManagerTest, AssignRemainingIndexes);
-
-  // Accessor to stored Label instances. For testing only.
-  const LabelVector& Labels() const { return labels_; }
-
-  // Directly assign |labels_|. For testing only.
-  void SetLabels(const LabelVector& labels);
-
-  DISALLOW_COPY_AND_ASSIGN(LabelManagerImpl);
+  DISALLOW_COPY_AND_ASSIGN(LabelManager);
 };
 
 }  // namespace courgette
diff --git a/courgette/label_manager_unittest.cc b/courgette/label_manager_unittest.cc
index 4b91d92..e95b513 100644
--- a/courgette/label_manager_unittest.cc
+++ b/courgette/label_manager_unittest.cc
@@ -16,35 +16,23 @@
 
 #include "base/logging.h"
 #include "base/macros.h"
+#include "courgette/image_utils.h"
 #include "testing/gtest/include/gtest/gtest.h"
 
 namespace courgette {
 
 namespace {
 
-// Test version of RvaVisitor: Just wrap std::vector<RVA>.
-class TestRvaVisitor : public LabelManagerImpl::RvaVisitor {
+class TestLabelManager : public LabelManager {
  public:
-  explicit TestRvaVisitor(std::vector<RVA>::const_iterator rva_begin,
-                          std::vector<RVA>::const_iterator rva_end)
-      : rva_it_(rva_begin), rva_end_(rva_end) {}
-
-  ~TestRvaVisitor() override {}
-
-  size_t Remaining() const override { return std::distance(rva_it_, rva_end_); }
-
-  RVA Get() const override { return *rva_it_; }
-
-  void Next() override { ++rva_it_; }
-
- private:
-  std::vector<RVA>::const_iterator rva_it_;
-  std::vector<RVA>::const_iterator rva_end_;
+  void SetLabels(const LabelVector& labels) {
+    labels_ = labels;
+  };
 };
 
 void CheckLabelManagerContent(LabelManager* label_manager,
                               const std::map<RVA, int32_t>& expected) {
-  EXPECT_EQ(expected.size(), label_manager->Size());
+  EXPECT_EQ(expected.size(), label_manager->Labels().size());
   for (const auto& rva_and_count : expected) {
     Label* label = label_manager->Find(rva_and_count.first);
     EXPECT_TRUE(label != nullptr);
@@ -111,18 +99,18 @@
 
 }  // namespace
 
-TEST(LabelManagerTest, GetIndexBound_LabelVector) {
+TEST(LabelManagerTest, GetLabelIndexBound) {
   LabelVector labels0;
-  EXPECT_EQ(0, LabelManager::GetIndexBound(labels0));
+  EXPECT_EQ(0, LabelManager::GetLabelIndexBound(labels0));
 
   LabelVector labels1_uninit = CreateLabelVectorBasic(1);
   ASSERT_EQ(1U, labels1_uninit.size());
-  EXPECT_EQ(0, LabelManager::GetIndexBound(labels1_uninit));
+  EXPECT_EQ(0, LabelManager::GetLabelIndexBound(labels1_uninit));
 
   LabelVector labels1_init = CreateLabelVectorBasic(1);
   ASSERT_EQ(1U, labels1_init.size());
   labels1_init[0].index_ = 99;
-  EXPECT_EQ(100, LabelManager::GetIndexBound(labels1_init));
+  EXPECT_EQ(100, LabelManager::GetLabelIndexBound(labels1_init));
 
   LabelVector labels6_mixed = CreateLabelVectorBasic(6);
   ASSERT_EQ(6U, labels6_mixed.size());
@@ -130,28 +118,7 @@
   labels6_mixed[2].index_ = 2;
   labels6_mixed[4].index_ = 15;
   labels6_mixed[5].index_ = 7;
-  EXPECT_EQ(16, LabelManager::GetIndexBound(labels6_mixed));
-}
-
-TEST(LabelManagerTest, GetIndexBound_RVAToLabel) {
-  RVAToLabel labels_map0;
-  EXPECT_EQ(0, LabelManager::GetIndexBound(labels_map0));
-
-  RVAToLabel labels1_map_init;
-  Label label1(static_cast<RVA>(0), 99, 1);
-  labels1_map_init[label1.rva_] = &label1;
-  EXPECT_EQ(100, LabelManager::GetIndexBound(labels1_map_init));
-
-  RVAToLabel labels_map6_mixed;
-  Label labels6[] = {
-    Label(static_cast<RVA>(1), 5, 1),
-    Label(static_cast<RVA>(2), 2, 1),
-    Label(static_cast<RVA>(4), 15, 1),
-    Label(static_cast<RVA>(5), 7, 1)
-  };
-  for (Label& label : labels6)
-    labels_map6_mixed[label.rva_] = &label;
-  EXPECT_EQ(16, LabelManager::GetIndexBound(labels_map6_mixed));
+  EXPECT_EQ(16, LabelManager::GetLabelIndexBound(labels6_mixed));
 }
 
 TEST(LabelManagerTest, Basic) {
@@ -169,10 +136,10 @@
   };
   std::vector<RVA> test_targets(std::begin(kTestTargetsRaw),
                                 std::end(kTestTargetsRaw));
-  TestRvaVisitor visitor(test_targets.begin(), test_targets.end());
+  TrivialRvaVisitor visitor(test_targets);
 
   // Preallocate targets, then populate.
-  LabelManagerImpl label_manager;
+  TestLabelManager label_manager;
   label_manager.Read(&visitor);
 
   static const std::pair<RVA, int32_t> kExpected1Raw[] = {
@@ -205,10 +172,10 @@
   for (int dup = 1; dup < 8; ++dup) {
     // Test data: |dup| copies of kRva.
     std::vector<RVA> test_targets(dup, kRva);
-    TestRvaVisitor visitor(test_targets.begin(), test_targets.end());
-    LabelManagerImpl label_manager;
+    TrivialRvaVisitor visitor(test_targets);
+    TestLabelManager label_manager;
     label_manager.Read(&visitor);
-    EXPECT_EQ(1U, label_manager.Size());  // Deduped to 1 Label.
+    EXPECT_EQ(1U, label_manager.Labels().size());  // Deduped to 1 Label.
 
     Label* label = label_manager.Find(kRva);
     EXPECT_NE(nullptr, label);
@@ -224,16 +191,16 @@
 
 TEST(LabelManagerTest, Empty) {
   std::vector<RVA> empty_test_targets;
-  TestRvaVisitor visitor(empty_test_targets.begin(), empty_test_targets.end());
-  LabelManagerImpl label_manager;
+  TrivialRvaVisitor visitor(empty_test_targets);
+  TestLabelManager label_manager;
   label_manager.Read(&visitor);
-  EXPECT_EQ(0U, label_manager.Size());
+  EXPECT_EQ(0U, label_manager.Labels().size());
   for (RVA rva = 0U; rva < 16U; ++rva)
     EXPECT_EQ(nullptr, label_manager.Find(rva));
 }
 
 TEST(LabelManagerTest, EmptyAssign) {
-  LabelManagerImpl label_manager_empty;
+  TestLabelManager label_manager_empty;
   label_manager_empty.DefaultAssignIndexes();
   label_manager_empty.UnassignIndexes();
   label_manager_empty.AssignRemainingIndexes();
@@ -241,7 +208,7 @@
 
 TEST(LabelManagerTest, TrivialAssign) {
   for (size_t size = 0; size < 20; ++size) {
-    LabelManagerImpl label_manager;
+    TestLabelManager label_manager;
     label_manager.SetLabels(CreateLabelVectorBasic(size));
 
     // Sanity check.
@@ -267,7 +234,7 @@
 
 // Tests SimpleIndexAssigner fill strategies independently.
 TEST(LabelManagerTest, SimpleIndexAssigner) {
-  using SimpleIndexAssigner = LabelManagerImpl::SimpleIndexAssigner;
+  using SimpleIndexAssigner = LabelManager::SimpleIndexAssigner;
   // See CreateLabelVectorWithIndexes() explanation on how we encode LabelVector
   // |index_| values as a string.
   const struct TestCase {
@@ -384,7 +351,7 @@
     {"..FE..GD..", "ABFECHGDIJ"}, // Forward: "AB"; backward: "IJ"; in: "CH".
   };
   for (const auto& test_case : kTestCases) {
-    LabelManagerImpl label_manager;
+    TestLabelManager label_manager;
     label_manager.SetLabels(CreateLabelVectorWithIndexes(test_case.input));
 
     label_manager.AssignRemainingIndexes();
diff --git a/device/usb/android/java/src/org/chromium/device/usb/ChromeUsbDevice.java b/device/usb/android/java/src/org/chromium/device/usb/ChromeUsbDevice.java
index 92e4e148..38b78e5 100644
--- a/device/usb/android/java/src/org/chromium/device/usb/ChromeUsbDevice.java
+++ b/device/usb/android/java/src/org/chromium/device/usb/ChromeUsbDevice.java
@@ -37,6 +37,21 @@
     }
 
     @CalledByNative
+    private int getDeviceClass() {
+        return mDevice.getDeviceClass();
+    }
+
+    @CalledByNative
+    private int getDeviceSubclass() {
+        return mDevice.getDeviceSubclass();
+    }
+
+    @CalledByNative
+    private int getDeviceProtocol() {
+        return mDevice.getDeviceProtocol();
+    }
+
+    @CalledByNative
     private int getVendorId() {
         return mDevice.getVendorId();
     }
@@ -46,6 +61,19 @@
         return mDevice.getProductId();
     }
 
+    @TargetApi(Build.VERSION_CODES.M)
+    @CalledByNative
+    private int getDeviceVersion() {
+        // The Android framework generates this string with:
+        // Integer.toString(version >> 8) + "." + (version & 0xFF)
+        //
+        // This is not technically correct because the low nibble is actually
+        // two separate version components (per spec). This undoes it at least.
+        String[] parts = mDevice.getVersion().split("\\.");
+        assert parts.length == 2;
+        return Integer.parseInt(parts[0]) << 8 | Integer.parseInt(parts[1]);
+    }
+
     @CalledByNative
     private String getManufacturerName() {
         return mDevice.getManufacturerName();
diff --git a/device/usb/mock_usb_device.cc b/device/usb/mock_usb_device.cc
index 49b2252..0f6c49c 100644
--- a/device/usb/mock_usb_device.cc
+++ b/device/usb/mock_usb_device.cc
@@ -16,8 +16,13 @@
                              const std::string& manufacturer_string,
                              const std::string& product_string,
                              const std::string& serial_number)
-    : UsbDevice(vendor_id,
+    : UsbDevice(0x0200,  // usb_version
+                0xff,    // device_class
+                0xff,    // device_subclass
+                0xff,    // device_protocol
+                vendor_id,
                 product_id,
+                0x0100,  // device_version
                 base::UTF8ToUTF16(manufacturer_string),
                 base::UTF8ToUTF16(product_string),
                 base::UTF8ToUTF16(serial_number)) {}
@@ -28,8 +33,13 @@
                              const std::string& product_string,
                              const std::string& serial_number,
                              const GURL& webusb_landing_page)
-    : UsbDevice(vendor_id,
+    : UsbDevice(0x0200,  // usb_version
+                0xff,    // device_class
+                0xff,    // device_subclass
+                0xff,    // device_protocol
+                vendor_id,
                 product_id,
+                0x0100,  // device_version
                 base::UTF8ToUTF16(manufacturer_string),
                 base::UTF8ToUTF16(product_string),
                 base::UTF8ToUTF16(serial_number)) {
diff --git a/device/usb/mojo/type_converters.cc b/device/usb/mojo/type_converters.cc
index 1761f0a..f6d84af 100644
--- a/device/usb/mojo/type_converters.cc
+++ b/device/usb/mojo/type_converters.cc
@@ -257,8 +257,17 @@
     const device::UsbDevice& device) {
   device::usb::DeviceInfoPtr info = device::usb::DeviceInfo::New();
   info->guid = device.guid();
+  info->usb_version_major = device.usb_version() >> 8;
+  info->usb_version_minor = device.usb_version() >> 4 & 0xf;
+  info->usb_version_subminor = device.usb_version() & 0xf;
+  info->class_code = device.device_class();
+  info->subclass_code = device.device_subclass();
+  info->protocol_code = device.device_protocol();
   info->vendor_id = device.vendor_id();
   info->product_id = device.product_id();
+  info->device_version_major = device.device_version() >> 8;
+  info->device_version_minor = device.device_version() >> 4 & 0xf;
+  info->device_version_subminor = device.device_version() & 0xf;
   info->manufacturer_name = base::UTF16ToUTF8(device.manufacturer_string());
   info->product_name = base::UTF16ToUTF8(device.product_string());
   info->serial_number = base::UTF16ToUTF8(device.serial_number());
diff --git a/device/usb/usb_device.cc b/device/usb/usb_device.cc
index d34e3e0..81be842 100644
--- a/device/usb/usb_device.cc
+++ b/device/usb/usb_device.cc
@@ -13,8 +13,13 @@
 
 void UsbDevice::Observer::OnDeviceRemoved(scoped_refptr<UsbDevice> device) {}
 
-UsbDevice::UsbDevice(uint16_t vendor_id,
+UsbDevice::UsbDevice(uint16_t usb_version,
+                     uint8_t device_class,
+                     uint8_t device_subclass,
+                     uint8_t device_protocol,
+                     uint16_t vendor_id,
                      uint16_t product_id,
+                     uint16_t device_version,
                      const base::string16& manufacturer_string,
                      const base::string16& product_string,
                      const base::string16& serial_number)
@@ -22,8 +27,13 @@
       product_string_(product_string),
       serial_number_(serial_number),
       guid_(base::GenerateGUID()),
+      usb_version_(usb_version),
+      device_class_(device_class),
+      device_subclass_(device_subclass),
+      device_protocol_(device_protocol),
       vendor_id_(vendor_id),
-      product_id_(product_id) {}
+      product_id_(product_id),
+      device_version_(device_version) {}
 
 UsbDevice::~UsbDevice() {
 }
diff --git a/device/usb/usb_device.h b/device/usb/usb_device.h
index 599c230..6450984 100644
--- a/device/usb/usb_device.h
+++ b/device/usb/usb_device.h
@@ -50,8 +50,13 @@
   const std::string& guid() const { return guid_; }
 
   // Accessors to basic information.
+  uint16_t usb_version() const { return usb_version_; }
+  uint8_t device_class() const { return device_class_; }
+  uint8_t device_subclass() const { return device_subclass_; }
+  uint8_t device_protocol() const { return device_protocol_; }
   uint16_t vendor_id() const { return vendor_id_; }
   uint16_t product_id() const { return product_id_; }
+  uint16_t device_version() const { return device_version_; }
   const base::string16& manufacturer_string() const {
     return manufacturer_string_;
   }
@@ -83,8 +88,13 @@
  protected:
   friend class UsbService;
 
-  UsbDevice(uint16_t vendor_id,
+  UsbDevice(uint16_t usb_version,
+            uint8_t device_class,
+            uint8_t device_subclass,
+            uint8_t device_protocol,
+            uint16_t vendor_id,
             uint16_t product_id,
+            uint16_t device_version,
             const base::string16& manufacturer_string,
             const base::string16& product_string,
             const base::string16& serial_number);
@@ -108,8 +118,13 @@
   friend class base::RefCountedThreadSafe<UsbDevice>;
 
   const std::string guid_;
+  const uint16_t usb_version_;
+  const uint8_t device_class_;
+  const uint8_t device_subclass_;
+  const uint8_t device_protocol_;
   const uint16_t vendor_id_;
   const uint16_t product_id_;
+  const uint16_t device_version_;
 
   base::ObserverList<Observer, true> observer_list_;
 
diff --git a/device/usb/usb_device_android.cc b/device/usb/usb_device_android.cc
index b1a2baa..53873a9 100644
--- a/device/usb/usb_device_android.cc
+++ b/device/usb/usb_device_android.cc
@@ -32,8 +32,9 @@
     const JavaRef<jobject>& usb_device) {
   ScopedJavaLocalRef<jobject> wrapper =
       Java_ChromeUsbDevice_create(env, usb_device.obj());
-  uint16_t vendor_id = Java_ChromeUsbDevice_getVendorId(env, wrapper.obj());
-  uint16_t product_id = Java_ChromeUsbDevice_getProductId(env, wrapper.obj());
+  uint16_t device_version = 0;
+  if (base::android::BuildInfo::GetInstance()->sdk_int() >= 23)
+    device_version = Java_ChromeUsbDevice_getDeviceVersion(env, wrapper.obj());
   ScopedJavaLocalRef<jstring> manufacturer_string =
       Java_ChromeUsbDevice_getManufacturerName(env, wrapper.obj());
   ScopedJavaLocalRef<jstring> product_string =
@@ -41,7 +42,13 @@
   ScopedJavaLocalRef<jstring> serial_number =
       Java_ChromeUsbDevice_getSerialNumber(env, wrapper.obj());
   return make_scoped_refptr(new UsbDeviceAndroid(
-      env, vendor_id, product_id,
+      env,
+      0x0200,  // USB protocol version, not provided by the Android API.
+      Java_ChromeUsbDevice_getDeviceClass(env, wrapper.obj()),
+      Java_ChromeUsbDevice_getDeviceSubclass(env, wrapper.obj()),
+      Java_ChromeUsbDevice_getDeviceProtocol(env, wrapper.obj()),
+      Java_ChromeUsbDevice_getVendorId(env, wrapper.obj()),
+      Java_ChromeUsbDevice_getProductId(env, wrapper.obj()), device_version,
       ConvertJavaStringToUTF16(env, manufacturer_string),
       ConvertJavaStringToUTF16(env, product_string),
       ConvertJavaStringToUTF16(env, serial_number), wrapper));
@@ -57,14 +64,24 @@
 }
 
 UsbDeviceAndroid::UsbDeviceAndroid(JNIEnv* env,
+                                   uint16_t usb_version,
+                                   uint8_t device_class,
+                                   uint8_t device_subclass,
+                                   uint8_t device_protocol,
                                    uint16_t vendor_id,
                                    uint16_t product_id,
+                                   uint16_t device_version,
                                    const base::string16& manufacturer_string,
                                    const base::string16& product_string,
                                    const base::string16& serial_number,
                                    const JavaRef<jobject>& wrapper)
-    : UsbDevice(vendor_id,
+    : UsbDevice(usb_version,
+                device_class,
+                device_subclass,
+                device_protocol,
+                vendor_id,
                 product_id,
+                device_version,
                 manufacturer_string,
                 product_string,
                 serial_number) {
diff --git a/device/usb/usb_device_android.h b/device/usb/usb_device_android.h
index adbb20f..9355837 100644
--- a/device/usb/usb_device_android.h
+++ b/device/usb/usb_device_android.h
@@ -25,8 +25,13 @@
 
  private:
   UsbDeviceAndroid(JNIEnv* env,
+                   uint16_t usb_version,
+                   uint8_t device_class,
+                   uint8_t device_subclass,
+                   uint8_t device_protocol,
                    uint16_t vendor_id,
                    uint16_t product_id,
+                   uint16_t device_version,
                    const base::string16& manufacturer_string,
                    const base::string16& product_string,
                    const base::string16& serial_number,
diff --git a/device/usb/usb_device_impl.cc b/device/usb/usb_device_impl.cc
index 0b8be8143..30220b1 100644
--- a/device/usb/usb_device_impl.cc
+++ b/device/usb/usb_device_impl.cc
@@ -144,11 +144,15 @@
 UsbDeviceImpl::UsbDeviceImpl(
     scoped_refptr<UsbContext> context,
     PlatformUsbDevice platform_device,
-    uint16_t vendor_id,
-    uint16_t product_id,
+    const libusb_device_descriptor& descriptor,
     scoped_refptr<base::SequencedTaskRunner> blocking_task_runner)
-    : UsbDevice(vendor_id,
-                product_id,
+    : UsbDevice(descriptor.bcdUSB,
+                descriptor.bDeviceClass,
+                descriptor.bDeviceSubClass,
+                descriptor.bDeviceProtocol,
+                descriptor.idVendor,
+                descriptor.idProduct,
+                descriptor.bcdDevice,
                 base::string16(),
                 base::string16(),
                 base::string16()),
diff --git a/device/usb/usb_device_impl.h b/device/usb/usb_device_impl.h
index f606816..4c94485a2 100644
--- a/device/usb/usb_device_impl.h
+++ b/device/usb/usb_device_impl.h
@@ -20,8 +20,9 @@
 #include "device/usb/webusb_descriptors.h"
 
 struct libusb_device;
-struct libusb_config_descriptor;
+struct libusb_device_descriptor;
 struct libusb_device_handle;
+struct libusb_config_descriptor;
 
 namespace base {
 class SequencedTaskRunner;
@@ -76,8 +77,7 @@
   // Called by UsbServiceImpl only;
   UsbDeviceImpl(scoped_refptr<UsbContext> context,
                 PlatformUsbDevice platform_device,
-                uint16_t vendor_id,
-                uint16_t product_id,
+                const libusb_device_descriptor& descriptor,
                 scoped_refptr<base::SequencedTaskRunner> blocking_task_runner);
 
   ~UsbDeviceImpl() override;
diff --git a/device/usb/usb_service_impl.cc b/device/usb/usb_service_impl.cc
index fd42ea6..c16aee3 100644
--- a/device/usb/usb_service_impl.cc
+++ b/device/usb/usb_service_impl.cc
@@ -490,9 +490,8 @@
       return;
     }
 
-    scoped_refptr<UsbDeviceImpl> device(
-        new UsbDeviceImpl(context_, platform_device, descriptor.idVendor,
-                          descriptor.idProduct, blocking_task_runner_));
+    scoped_refptr<UsbDeviceImpl> device(new UsbDeviceImpl(
+        context_, platform_device, descriptor, blocking_task_runner_));
     base::Closure add_device =
         base::Bind(&UsbServiceImpl::AddDevice, weak_factory_.GetWeakPtr(),
                    refresh_complete, device);
diff --git a/extensions/browser/api/usb/usb_guid_map.cc b/extensions/browser/api/usb/usb_guid_map.cc
index 0cb3ce85..8d65d07a 100644
--- a/extensions/browser/api/usb/usb_guid_map.cc
+++ b/extensions/browser/api/usb/usb_guid_map.cc
@@ -56,6 +56,7 @@
   device_out->device = GetIdFromGuid(device_in->guid());
   device_out->vendor_id = device_in->vendor_id();
   device_out->product_id = device_in->product_id();
+  device_out->version = device_in->device_version();
   device_out->product_name = base::UTF16ToUTF8(device_in->product_string());
   device_out->manufacturer_name =
       base::UTF16ToUTF8(device_in->manufacturer_string());
diff --git a/extensions/common/api/usb.idl b/extensions/common/api/usb.idl
index 21e4bd3c..f0d42eb 100644
--- a/extensions/common/api/usb.idl
+++ b/extensions/common/api/usb.idl
@@ -31,6 +31,8 @@
     long vendorId;
     // The product ID.
     long productId;
+    // The device version (bcdDevice field).
+    long version;
     // The iProduct string read from the device, if available.
     DOMString productName;
     // The iManufacturer string read from the device, if available.
diff --git a/extensions/test/data/api_test/usb/device_handling/test.js b/extensions/test/data/api_test/usb/device_handling/test.js
index 5914f6a..b1d5252 100644
--- a/extensions/test/data/api_test/usb/device_handling/test.js
+++ b/extensions/test/data/api_test/usb/device_handling/test.js
@@ -11,6 +11,7 @@
   }, function(devices) {
     chrome.test.assertEq(1, devices.length);
     var device = devices[0];
+    chrome.test.assertEq(0x0100, device.version);
     chrome.test.assertEq("Test Device", device.productName);
     chrome.test.assertEq("Test Manufacturer", device.manufacturerName);
     chrome.test.assertEq("ABC123", device.serialNumber);
diff --git a/gpu/command_buffer/client/gpu_memory_buffer_manager.h b/gpu/command_buffer/client/gpu_memory_buffer_manager.h
index c95f841..a3385325 100644
--- a/gpu/command_buffer/client/gpu_memory_buffer_manager.h
+++ b/gpu/command_buffer/client/gpu_memory_buffer_manager.h
@@ -22,7 +22,8 @@
   virtual scoped_ptr<gfx::GpuMemoryBuffer> AllocateGpuMemoryBuffer(
       const gfx::Size& size,
       gfx::BufferFormat format,
-      gfx::BufferUsage usage) = 0;
+      gfx::BufferUsage usage,
+      int32_t surface_id) = 0;
 
   // Creates a GpuMemoryBuffer from existing handle.
   virtual scoped_ptr<gfx::GpuMemoryBuffer> CreateGpuMemoryBufferFromHandle(
diff --git a/gpu/command_buffer/service/buffer_manager.cc b/gpu/command_buffer/service/buffer_manager.cc
index 3281d76..b335219 100644
--- a/gpu/command_buffer/service/buffer_manager.cc
+++ b/gpu/command_buffer/service/buffer_manager.cc
@@ -389,6 +389,12 @@
     return;
   }
 
+  if (size > 1024 * 1024 * 1024) {
+    ERRORSTATE_SET_GL_ERROR(error_state, GL_OUT_OF_MEMORY, "glBufferData",
+                            "cannot allocate more than 1GB.");
+    return;
+  }
+
   Buffer* buffer = GetBufferInfoForTarget(context_state, target);
   if (!buffer) {
     ERRORSTATE_SET_GL_ERROR(
diff --git a/gpu/command_buffer/service/in_process_command_buffer.cc b/gpu/command_buffer/service/in_process_command_buffer.cc
index 55e5a19..9483bf1 100644
--- a/gpu/command_buffer/service/in_process_command_buffer.cc
+++ b/gpu/command_buffer/service/in_process_command_buffer.cc
@@ -826,7 +826,7 @@
       gpu_memory_buffer_manager_->AllocateGpuMemoryBuffer(
           gfx::Size(width, height),
           gpu::DefaultBufferFormatForImageFormat(internalformat),
-          gfx::BufferUsage::SCANOUT));
+          gfx::BufferUsage::SCANOUT, 0 /* surface_id */));
   if (!buffer)
     return -1;
 
diff --git a/gpu/ipc/client/command_buffer_proxy_impl.cc b/gpu/ipc/client/command_buffer_proxy_impl.cc
index 07fc636..99474e6c27 100644
--- a/gpu/ipc/client/command_buffer_proxy_impl.cc
+++ b/gpu/ipc/client/command_buffer_proxy_impl.cc
@@ -480,7 +480,7 @@
       channel_->gpu_memory_buffer_manager()->AllocateGpuMemoryBuffer(
           gfx::Size(width, height),
           gpu::DefaultBufferFormatForImageFormat(internal_format),
-          gfx::BufferUsage::SCANOUT));
+          gfx::BufferUsage::SCANOUT, 0 /* surface_id */));
   if (!buffer)
     return -1;
 
diff --git a/media/capture/content/screen_capture_device_core.cc b/media/capture/content/screen_capture_device_core.cc
index 2b3f3cf..6e9f335 100644
--- a/media/capture/content/screen_capture_device_core.cc
+++ b/media/capture/content/screen_capture_device_core.cc
@@ -65,6 +65,17 @@
   TransitionStateTo(kCapturing);
 }
 
+void ScreenCaptureDeviceCore::RequestRefreshFrame() {
+  DCHECK(thread_checker_.CalledOnValidThread());
+
+  if (state_ != kCapturing)
+    return;
+
+  if (oracle_proxy_->AttemptPassiveRefresh())
+    return;
+  capture_machine_->MaybeCaptureForRefresh();
+}
+
 void ScreenCaptureDeviceCore::StopAndDeAllocate() {
   DCHECK(thread_checker_.CalledOnValidThread());
 
diff --git a/media/capture/content/screen_capture_device_core.h b/media/capture/content/screen_capture_device_core.h
index 7e301545..057e894 100644
--- a/media/capture/content/screen_capture_device_core.h
+++ b/media/capture/content/screen_capture_device_core.h
@@ -46,6 +46,18 @@
   // overloading or under-utilization.
   virtual bool IsAutoThrottlingEnabled() const;
 
+  // Called by ScreenCaptureDeviceCore when it failed to satisfy a "refresh
+  // frame" request by attempting to resurrect the last video frame from the
+  // buffer pool (this is referred to as the "passive" refresh approach).  The
+  // failure can happen for a number of reasons (e.g., the oracle decided to
+  // change resolution, or consumers of the last video frame are not yet
+  // finished with it).
+  //
+  // The implementation of this method should consult the oracle, using the
+  // kActiveRefreshRequest event type, to decide whether to initiate a new frame
+  // capture, and then do so if the oracle agrees.
+  virtual void MaybeCaptureForRefresh() = 0;
+
  private:
   DISALLOW_COPY_AND_ASSIGN(VideoCaptureMachine);
 };
@@ -69,6 +81,7 @@
   // Asynchronous requests to change ScreenCaptureDeviceCore state.
   void AllocateAndStart(const VideoCaptureParams& params,
                         scoped_ptr<VideoCaptureDevice::Client> client);
+  void RequestRefreshFrame();
   void StopAndDeAllocate();
 
  private:
diff --git a/media/capture/content/smooth_event_sampler.cc b/media/capture/content/smooth_event_sampler.cc
index 9ac263d..7f7297f2 100644
--- a/media/capture/content/smooth_event_sampler.cc
+++ b/media/capture/content/smooth_event_sampler.cc
@@ -12,11 +12,8 @@
 
 namespace media {
 
-SmoothEventSampler::SmoothEventSampler(base::TimeDelta min_capture_period,
-                                       int redundant_capture_goal)
-    : redundant_capture_goal_(redundant_capture_goal),
-      overdue_sample_count_(0),
-      token_bucket_(base::TimeDelta::Max()) {
+SmoothEventSampler::SmoothEventSampler(base::TimeDelta min_capture_period)
+    : token_bucket_(base::TimeDelta::Max()) {
   SetMinCapturePeriod(min_capture_period);
 }
 
@@ -59,29 +56,8 @@
   TRACE_COUNTER1("gpu.capture", "MirroringTokenBucketUsec",
                  std::max<int64_t>(0, token_bucket_.InMicroseconds()));
 
-  if (HasUnrecordedEvent()) {
+  if (HasUnrecordedEvent())
     last_sample_ = current_event_;
-    overdue_sample_count_ = 0;
-  } else {
-    ++overdue_sample_count_;
-  }
-}
-
-bool SmoothEventSampler::IsOverdueForSamplingAt(
-    base::TimeTicks event_time) const {
-  DCHECK(!event_time.is_null());
-
-  if (!HasUnrecordedEvent() && overdue_sample_count_ >= redundant_capture_goal_)
-    return false;  // Not dirty.
-
-  if (last_sample_.is_null())
-    return true;
-
-  // If we're dirty but not yet old, then we've recently gotten updates, so we
-  // won't request a sample just yet.
-  base::TimeDelta dirty_interval = event_time - last_sample_;
-  return dirty_interval >=
-         base::TimeDelta::FromMilliseconds(OVERDUE_DIRTY_THRESHOLD_MILLIS);
 }
 
 bool SmoothEventSampler::HasUnrecordedEvent() const {
diff --git a/media/capture/content/smooth_event_sampler.h b/media/capture/content/smooth_event_sampler.h
index 6b69a10..748ad15 100644
--- a/media/capture/content/smooth_event_sampler.h
+++ b/media/capture/content/smooth_event_sampler.h
@@ -14,15 +14,7 @@
 // Filters a sequence of events to achieve a target frequency.
 class MEDIA_EXPORT SmoothEventSampler {
  public:
-  enum {
-    // The maximum amount of time that can elapse before considering unchanged
-    // content as dirty for the purposes of timer-based overdue sampling.  This
-    // is the same value found in cc::FrameRateCounter.
-    OVERDUE_DIRTY_THRESHOLD_MILLIS = 250  // 4 FPS
-  };
-
-  SmoothEventSampler(base::TimeDelta min_capture_period,
-                     int redundant_capture_goal);
+  explicit SmoothEventSampler(base::TimeDelta min_capture_period);
 
   // Get/Set minimum capture period. When setting a new value, the state of the
   // sampler is retained so that sampling will continue smoothly.
@@ -42,22 +34,16 @@
   // we have sampled the most recent event.
   void RecordSample();
 
-  // Returns true if, at time |event_time|, sampling should occur because too
-  // much time will have passed relative to the last event and/or sample.
-  bool IsOverdueForSamplingAt(base::TimeTicks event_time) const;
-
   // Returns true if ConsiderPresentationEvent() has been called since the last
   // call to RecordSample().
   bool HasUnrecordedEvent() const;
 
  private:
   base::TimeDelta min_capture_period_;
-  const int redundant_capture_goal_;
   base::TimeDelta token_bucket_capacity_;
 
   base::TimeTicks current_event_;
   base::TimeTicks last_sample_;
-  int overdue_sample_count_;
   base::TimeDelta token_bucket_;
 
   DISALLOW_COPY_AND_ASSIGN(SmoothEventSampler);
diff --git a/media/capture/content/smooth_event_sampler_unittest.cc b/media/capture/content/smooth_event_sampler_unittest.cc
index 428a8630..abd7d4cc 100644
--- a/media/capture/content/smooth_event_sampler_unittest.cc
+++ b/media/capture/content/smooth_event_sampler_unittest.cc
@@ -28,9 +28,7 @@
   ASSERT_TRUE(sampler->HasUnrecordedEvent());
   sampler->RecordSample();
   ASSERT_FALSE(sampler->HasUnrecordedEvent());
-  ASSERT_FALSE(sampler->IsOverdueForSamplingAt(*t));
   *t += vsync;
-  ASSERT_FALSE(sampler->IsOverdueForSamplingAt(*t));
 }
 
 void SteadyStateNoSampleAndAdvance(base::TimeDelta vsync,
@@ -38,44 +36,13 @@
                                    base::TimeTicks* t) {
   ASSERT_FALSE(AddEventAndConsiderSampling(sampler, *t));
   ASSERT_TRUE(sampler->HasUnrecordedEvent());
-  ASSERT_FALSE(sampler->IsOverdueForSamplingAt(*t));
   *t += vsync;
-  ASSERT_FALSE(sampler->IsOverdueForSamplingAt(*t));
 }
 
 base::TimeTicks InitialTestTimeTicks() {
   return base::TimeTicks() + base::TimeDelta::FromSeconds(1);
 }
 
-void TestRedundantCaptureStrategy(base::TimeDelta capture_period,
-                                  int redundant_capture_goal,
-                                  SmoothEventSampler* sampler,
-                                  base::TimeTicks* t) {
-  // Before any events have been considered, we're overdue for sampling.
-  ASSERT_TRUE(sampler->IsOverdueForSamplingAt(*t));
-
-  // Consider the first event.  We want to sample that.
-  ASSERT_FALSE(sampler->HasUnrecordedEvent());
-  ASSERT_TRUE(AddEventAndConsiderSampling(sampler, *t));
-  ASSERT_TRUE(sampler->HasUnrecordedEvent());
-  sampler->RecordSample();
-  ASSERT_FALSE(sampler->HasUnrecordedEvent());
-
-  // After more than 250 ms has passed without considering an event, we should
-  // repeatedly be overdue for sampling.  However, once the redundant capture
-  // goal is achieved, we should no longer be overdue for sampling.
-  *t += base::TimeDelta::FromMilliseconds(250);
-  for (int i = 0; i < redundant_capture_goal; i++) {
-    SCOPED_TRACE(base::StringPrintf("Iteration %d", i));
-    ASSERT_FALSE(sampler->HasUnrecordedEvent());
-    ASSERT_TRUE(sampler->IsOverdueForSamplingAt(*t))
-        << "Should sample until redundant capture goal is hit";
-    sampler->RecordSample();
-    *t += capture_period;  // Timer fires once every capture period.
-  }
-  ASSERT_FALSE(sampler->IsOverdueForSamplingAt(*t))
-      << "Should not be overdue once redundant capture goal achieved.";
-}
 
 }  // namespace
 
@@ -83,15 +50,11 @@
 // much more comprehensive before/after/edge-case scenarios than the others.
 TEST(SmoothEventSamplerTest, Sample60HertzAt30Hertz) {
   const base::TimeDelta capture_period = base::TimeDelta::FromSeconds(1) / 30;
-  const int redundant_capture_goal = 200;
   const base::TimeDelta vsync = base::TimeDelta::FromSeconds(1) / 60;
 
-  SmoothEventSampler sampler(capture_period, redundant_capture_goal);
+  SmoothEventSampler sampler(capture_period);
   base::TimeTicks t = InitialTestTimeTicks();
 
-  TestRedundantCaptureStrategy(capture_period, redundant_capture_goal, &sampler,
-                               &t);
-
   // Steady state, we should capture every other vsync, indefinitely.
   for (int i = 0; i < 100; i++) {
     SCOPED_TRACE(base::StringPrintf("Iteration %d", i));
@@ -103,7 +66,6 @@
   // case we are adding events but not sampling them.
   for (int i = 0; i < 20; i++) {
     SCOPED_TRACE(base::StringPrintf("Iteration %d", i));
-    ASSERT_EQ(i >= 14, sampler.IsOverdueForSamplingAt(t));
     ASSERT_TRUE(AddEventAndConsiderSampling(&sampler, t));
     ASSERT_TRUE(sampler.HasUnrecordedEvent());
     t += vsync;
@@ -111,7 +73,6 @@
 
   // Now suppose we can sample again. We should be back in the steady state,
   // but at a different phase.
-  ASSERT_TRUE(sampler.IsOverdueForSamplingAt(t));
   for (int i = 0; i < 100; i++) {
     SCOPED_TRACE(base::StringPrintf("Iteration %d", i));
     SteadyStateSampleAndAdvance(vsync, &sampler, &t);
@@ -122,15 +83,11 @@
 // 50Hz sampled at 30Hz should produce a sequence where some frames are skipped.
 TEST(SmoothEventSamplerTest, Sample50HertzAt30Hertz) {
   const base::TimeDelta capture_period = base::TimeDelta::FromSeconds(1) / 30;
-  const int redundant_capture_goal = 2;
   const base::TimeDelta vsync = base::TimeDelta::FromSeconds(1) / 50;
 
-  SmoothEventSampler sampler(capture_period, redundant_capture_goal);
+  SmoothEventSampler sampler(capture_period);
   base::TimeTicks t = InitialTestTimeTicks();
 
-  TestRedundantCaptureStrategy(capture_period, redundant_capture_goal, &sampler,
-                               &t);
-
   // Steady state, we should capture 1st, 2nd and 4th frames out of every five
   // frames, indefinitely.
   for (int i = 0; i < 100; i++) {
@@ -146,14 +103,12 @@
   // case we are adding events but not sampling them.
   for (int i = 0; i < 20; i++) {
     SCOPED_TRACE(base::StringPrintf("Iteration %d", i));
-    ASSERT_EQ(i >= 11, sampler.IsOverdueForSamplingAt(t));
     ASSERT_TRUE(AddEventAndConsiderSampling(&sampler, t));
     t += vsync;
   }
 
   // Now suppose we can sample again. We should be back in the steady state
   // again.
-  ASSERT_TRUE(sampler.IsOverdueForSamplingAt(t));
   for (int i = 0; i < 100; i++) {
     SCOPED_TRACE(base::StringPrintf("Iteration %d", i));
     SteadyStateSampleAndAdvance(vsync, &sampler, &t);
@@ -167,15 +122,11 @@
 // 75Hz sampled at 30Hz should produce a sequence where some frames are skipped.
 TEST(SmoothEventSamplerTest, Sample75HertzAt30Hertz) {
   const base::TimeDelta capture_period = base::TimeDelta::FromSeconds(1) / 30;
-  const int redundant_capture_goal = 32;
   const base::TimeDelta vsync = base::TimeDelta::FromSeconds(1) / 75;
 
-  SmoothEventSampler sampler(capture_period, redundant_capture_goal);
+  SmoothEventSampler sampler(capture_period);
   base::TimeTicks t = InitialTestTimeTicks();
 
-  TestRedundantCaptureStrategy(capture_period, redundant_capture_goal, &sampler,
-                               &t);
-
   // Steady state, we should capture 1st and 3rd frames out of every five
   // frames, indefinitely.
   SteadyStateSampleAndAdvance(vsync, &sampler, &t);
@@ -193,14 +144,12 @@
   // case we are adding events but not sampling them.
   for (int i = 0; i < 20; i++) {
     SCOPED_TRACE(base::StringPrintf("Iteration %d", i));
-    ASSERT_EQ(i >= 16, sampler.IsOverdueForSamplingAt(t));
     ASSERT_TRUE(AddEventAndConsiderSampling(&sampler, t));
     t += vsync;
   }
 
   // Now suppose we can sample again. We capture the next frame, and not the one
   // after that, and then we're back in the steady state again.
-  ASSERT_TRUE(sampler.IsOverdueForSamplingAt(t));
   SteadyStateSampleAndAdvance(vsync, &sampler, &t);
   SteadyStateNoSampleAndAdvance(vsync, &sampler, &t);
   for (int i = 0; i < 100; i++) {
@@ -216,15 +165,11 @@
 // 30Hz sampled at 30Hz should produce 30Hz.
 TEST(SmoothEventSamplerTest, Sample30HertzAt30Hertz) {
   const base::TimeDelta capture_period = base::TimeDelta::FromSeconds(1) / 30;
-  const int redundant_capture_goal = 1;
   const base::TimeDelta vsync = base::TimeDelta::FromSeconds(1) / 30;
 
-  SmoothEventSampler sampler(capture_period, redundant_capture_goal);
+  SmoothEventSampler sampler(capture_period);
   base::TimeTicks t = InitialTestTimeTicks();
 
-  TestRedundantCaptureStrategy(capture_period, redundant_capture_goal, &sampler,
-                               &t);
-
   // Steady state, we should capture every vsync, indefinitely.
   for (int i = 0; i < 200; i++) {
     SCOPED_TRACE(base::StringPrintf("Iteration %d", i));
@@ -235,13 +180,11 @@
   // case we are adding events but not sampling them.
   for (int i = 0; i < 10; i++) {
     SCOPED_TRACE(base::StringPrintf("Iteration %d", i));
-    ASSERT_EQ(i >= 7, sampler.IsOverdueForSamplingAt(t));
     ASSERT_TRUE(AddEventAndConsiderSampling(&sampler, t));
     t += vsync;
   }
 
   // Now suppose we can sample again. We should be back in the steady state.
-  ASSERT_TRUE(sampler.IsOverdueForSamplingAt(t));
   for (int i = 0; i < 100; i++) {
     SCOPED_TRACE(base::StringPrintf("Iteration %d", i));
     SteadyStateSampleAndAdvance(vsync, &sampler, &t);
@@ -251,15 +194,11 @@
 // 24Hz sampled at 30Hz should produce 24Hz.
 TEST(SmoothEventSamplerTest, Sample24HertzAt30Hertz) {
   const base::TimeDelta capture_period = base::TimeDelta::FromSeconds(1) / 30;
-  const int redundant_capture_goal = 333;
   const base::TimeDelta vsync = base::TimeDelta::FromSeconds(1) / 24;
 
-  SmoothEventSampler sampler(capture_period, redundant_capture_goal);
+  SmoothEventSampler sampler(capture_period);
   base::TimeTicks t = InitialTestTimeTicks();
 
-  TestRedundantCaptureStrategy(capture_period, redundant_capture_goal, &sampler,
-                               &t);
-
   // Steady state, we should capture every vsync, indefinitely.
   for (int i = 0; i < 200; i++) {
     SCOPED_TRACE(base::StringPrintf("Iteration %d", i));
@@ -270,13 +209,11 @@
   // case we are adding events but not sampling them.
   for (int i = 0; i < 10; i++) {
     SCOPED_TRACE(base::StringPrintf("Iteration %d", i));
-    ASSERT_EQ(i >= 6, sampler.IsOverdueForSamplingAt(t));
     ASSERT_TRUE(AddEventAndConsiderSampling(&sampler, t));
     t += vsync;
   }
 
   // Now suppose we can sample again. We should be back in the steady state.
-  ASSERT_TRUE(sampler.IsOverdueForSamplingAt(t));
   for (int i = 0; i < 100; i++) {
     SCOPED_TRACE(base::StringPrintf("Iteration %d", i));
     SteadyStateSampleAndAdvance(vsync, &sampler, &t);
@@ -291,14 +228,10 @@
   const base::TimeDelta two_to_one_period = vsync * 2;
   const base::TimeDelta two_and_three_to_one_period =
       base::TimeDelta::FromSeconds(1) / 24;
-  const int redundant_capture_goal = 1;
 
-  SmoothEventSampler sampler(one_to_one_period, redundant_capture_goal);
+  SmoothEventSampler sampler(one_to_one_period);
   base::TimeTicks t = InitialTestTimeTicks();
 
-  TestRedundantCaptureStrategy(one_to_one_period, redundant_capture_goal,
-                               &sampler, &t);
-
   // With the capture rate at 60 Hz, we should capture every vsync.
   for (int i = 0; i < 100; i++) {
     SCOPED_TRACE(base::StringPrintf("Iteration %d", i));
@@ -335,30 +268,6 @@
   }
 }
 
-TEST(SmoothEventSamplerTest, DoubleDrawAtOneTimeStillDirties) {
-  const base::TimeDelta capture_period = base::TimeDelta::FromSeconds(1) / 30;
-  const base::TimeDelta overdue_period = base::TimeDelta::FromSeconds(1);
-
-  SmoothEventSampler sampler(capture_period, 1);
-  base::TimeTicks t = InitialTestTimeTicks();
-
-  ASSERT_TRUE(AddEventAndConsiderSampling(&sampler, t));
-  sampler.RecordSample();
-  ASSERT_FALSE(sampler.IsOverdueForSamplingAt(t))
-      << "Sampled last event; should not be dirty.";
-  t += overdue_period;
-
-  // Now simulate 2 events with the same clock value.
-  ASSERT_TRUE(AddEventAndConsiderSampling(&sampler, t));
-  sampler.RecordSample();
-  ASSERT_FALSE(AddEventAndConsiderSampling(&sampler, t))
-      << "Two events at same time -- expected second not to be sampled.";
-  ASSERT_TRUE(sampler.IsOverdueForSamplingAt(t + overdue_period))
-      << "Second event should dirty the capture state.";
-  sampler.RecordSample();
-  ASSERT_FALSE(sampler.IsOverdueForSamplingAt(t + overdue_period));
-}
-
 namespace {
 
 struct DataPoint {
@@ -459,7 +368,7 @@
                                           {true, 33.44},
                                           {false, 0}};
 
-  SmoothEventSampler sampler(base::TimeDelta::FromSeconds(1) / 30, 3);
+  SmoothEventSampler sampler(base::TimeDelta::FromSeconds(1) / 30);
   ReplayCheckingSamplerDecisions(data_points, arraysize(data_points), &sampler);
 }
 
@@ -568,7 +477,7 @@
                                           {true, 33.44},
                                           {true, 33.44}};
 
-  SmoothEventSampler sampler(base::TimeDelta::FromSeconds(1) / 30, 3);
+  SmoothEventSampler sampler(base::TimeDelta::FromSeconds(1) / 30);
   ReplayCheckingSamplerDecisions(data_points, arraysize(data_points), &sampler);
 }
 
@@ -701,7 +610,7 @@
                                           {true, 16.72},
                                           {true, 50.16}};
 
-  SmoothEventSampler sampler(base::TimeDelta::FromSeconds(1) / 30, 3);
+  SmoothEventSampler sampler(base::TimeDelta::FromSeconds(1) / 30);
   ReplayCheckingSamplerDecisions(data_points, arraysize(data_points), &sampler);
 }
 
diff --git a/media/capture/content/thread_safe_capture_oracle.cc b/media/capture/content/thread_safe_capture_oracle.cc
index f3ba5a4..e99b56c 100644
--- a/media/capture/content/thread_safe_capture_oracle.cc
+++ b/media/capture/content/thread_safe_capture_oracle.cc
@@ -11,6 +11,7 @@
 #include "base/bits.h"
 #include "base/logging.h"
 #include "base/memory/scoped_ptr.h"
+#include "base/numerics/safe_conversions.h"
 #include "base/synchronization/lock.h"
 #include "base/time/time.h"
 #include "base/trace_event/trace_event.h"
@@ -57,63 +58,80 @@
   // Grab the current time before waiting to acquire the |lock_|.
   const base::TimeTicks capture_begin_time = base::TimeTicks::Now();
 
-  base::AutoLock guard(lock_);
+  gfx::Size visible_size;
+  gfx::Size coded_size;
+  scoped_ptr<media::VideoCaptureDevice::Client::Buffer> output_buffer;
+  double attenuated_utilization;
+  int frame_number;
+  base::TimeDelta estimated_frame_duration;
+  {
+    base::AutoLock guard(lock_);
 
-  if (!client_)
-    return false;  // Capture is stopped.
+    if (!client_)
+      return false;  // Capture is stopped.
 
-  const bool should_capture =
-      oracle_.ObserveEventAndDecideCapture(event, damage_rect, event_time);
-  const gfx::Size visible_size = oracle_.capture_size();
-  // TODO(miu): Clients should request exact padding, instead of this
-  // memory-wasting hack to make frames that are compatible with all HW
-  // encoders.  http://crbug.com/555911
-  const gfx::Size coded_size(base::bits::Align(visible_size.width(), 16),
-                             base::bits::Align(visible_size.height(), 16));
-
-  scoped_ptr<media::VideoCaptureDevice::Client::Buffer> output_buffer(
-      client_->ReserveOutputBuffer(coded_size,
-                                   params_.requested_format.pixel_format,
-                                   params_.requested_format.pixel_storage));
-  // Get the current buffer pool utilization and attenuate it: The utilization
-  // reported to the oracle is in terms of a maximum sustainable amount (not the
-  // absolute maximum).
-  const double attenuated_utilization =
-      client_->GetBufferPoolUtilization() *
-      (100.0 / kTargetMaxPoolUtilizationPercent);
-
-  const char* event_name =
-      (event == VideoCaptureOracle::kTimerPoll
-           ? "poll"
-           : (event == VideoCaptureOracle::kCompositorUpdate ? "gpu"
-                                                             : "unknown"));
-
-  // Consider the various reasons not to initiate a capture.
-  if (should_capture && !output_buffer.get()) {
-    TRACE_EVENT_INSTANT1("gpu.capture", "PipelineLimited",
-                         TRACE_EVENT_SCOPE_THREAD, "trigger", event_name);
-    oracle_.RecordWillNotCapture(attenuated_utilization);
-    return false;
-  } else if (!should_capture && output_buffer.get()) {
-    if (event == VideoCaptureOracle::kCompositorUpdate) {
+    if (!oracle_.ObserveEventAndDecideCapture(event, damage_rect, event_time)) {
       // This is a normal and acceptable way to drop a frame. We've hit our
       // capture rate limit: for example, the content is animating at 60fps but
       // we're capturing at 30fps.
       TRACE_EVENT_INSTANT1("gpu.capture", "FpsRateLimited",
-                           TRACE_EVENT_SCOPE_THREAD, "trigger", event_name);
+                           TRACE_EVENT_SCOPE_THREAD, "trigger",
+                           VideoCaptureOracle::EventAsString(event));
+      return false;
     }
-    return false;
-  } else if (!should_capture && !output_buffer.get()) {
-    // We decided not to capture, but we wouldn't have been able to if we wanted
-    // to because no output buffer was available.
-    TRACE_EVENT_INSTANT1("gpu.capture", "NearlyPipelineLimited",
-                         TRACE_EVENT_SCOPE_THREAD, "trigger", event_name);
-    return false;
+
+    visible_size = oracle_.capture_size();
+    // TODO(miu): Clients should request exact padding, instead of this
+    // memory-wasting hack to make frames that are compatible with all HW
+    // encoders.  http://crbug.com/555911
+    coded_size.SetSize(base::bits::Align(visible_size.width(), 16),
+                       base::bits::Align(visible_size.height(), 16));
+
+    if (event == VideoCaptureOracle::kPassiveRefreshRequest) {
+      output_buffer = client_->ResurrectLastOutputBuffer(
+          coded_size, params_.requested_format.pixel_format,
+          params_.requested_format.pixel_storage);
+      if (!output_buffer) {
+        TRACE_EVENT_INSTANT0("gpu.capture", "ResurrectionFailed",
+                             TRACE_EVENT_SCOPE_THREAD);
+        return false;
+      }
+    } else {
+      output_buffer = client_->ReserveOutputBuffer(
+          coded_size, params_.requested_format.pixel_format,
+          params_.requested_format.pixel_storage);
+    }
+
+    // Get the current buffer pool utilization and attenuate it: The utilization
+    // reported to the oracle is in terms of a maximum sustainable amount (not
+    // the absolute maximum).
+    attenuated_utilization = client_->GetBufferPoolUtilization() *
+                             (100.0 / kTargetMaxPoolUtilizationPercent);
+
+    if (!output_buffer) {
+      TRACE_EVENT_INSTANT2(
+          "gpu.capture", "PipelineLimited", TRACE_EVENT_SCOPE_THREAD, "trigger",
+          VideoCaptureOracle::EventAsString(event), "atten_util_percent",
+          base::saturated_cast<int>(attenuated_utilization * 100.0 + 0.5));
+      oracle_.RecordWillNotCapture(attenuated_utilization);
+      return false;
+    }
+
+    frame_number = oracle_.RecordCapture(attenuated_utilization);
+    estimated_frame_duration = oracle_.estimated_frame_duration();
+  }  // End of critical section.
+
+  if (attenuated_utilization >= 1.0) {
+    TRACE_EVENT_INSTANT2(
+        "gpu.capture", "NearlyPipelineLimited", TRACE_EVENT_SCOPE_THREAD,
+        "trigger", VideoCaptureOracle::EventAsString(event),
+        "atten_util_percent",
+        base::saturated_cast<int>(attenuated_utilization * 100.0 + 0.5));
   }
 
-  const int frame_number = oracle_.RecordCapture(attenuated_utilization);
   TRACE_EVENT_ASYNC_BEGIN2("gpu.capture", "Capture", output_buffer.get(),
-                           "frame_number", frame_number, "trigger", event_name);
+                           "frame_number", frame_number, "trigger",
+                           VideoCaptureOracle::EventAsString(event));
 
   DCHECK_EQ(media::PIXEL_STORAGE_CPU, params_.requested_format.pixel_storage);
   *storage = VideoFrame::WrapExternalSharedMemory(
@@ -124,10 +142,25 @@
       base::TimeDelta());
   if (!(*storage))
     return false;
-  *callback =
-      base::Bind(&ThreadSafeCaptureOracle::DidCaptureFrame, this, frame_number,
-                 base::Passed(&output_buffer), capture_begin_time,
-                 oracle_.estimated_frame_duration());
+  *callback = base::Bind(&ThreadSafeCaptureOracle::DidCaptureFrame, this,
+                         frame_number, base::Passed(&output_buffer),
+                         capture_begin_time, estimated_frame_duration);
+
+  return true;
+}
+
+bool ThreadSafeCaptureOracle::AttemptPassiveRefresh() {
+  const base::TimeTicks refresh_time = base::TimeTicks::Now();
+
+  scoped_refptr<VideoFrame> frame;
+  CaptureFrameCallback capture_callback;
+  if (!ObserveEventAndDecideCapture(VideoCaptureOracle::kPassiveRefreshRequest,
+                                    gfx::Rect(), refresh_time, &frame,
+                                    &capture_callback)) {
+    return false;
+  }
+
+  capture_callback.Run(frame, refresh_time, true);
   return true;
 }
 
@@ -163,10 +196,11 @@
     const scoped_refptr<VideoFrame>& frame,
     base::TimeTicks timestamp,
     bool success) {
-  base::AutoLock guard(lock_);
   TRACE_EVENT_ASYNC_END2("gpu.capture", "Capture", buffer.get(), "success",
                          success, "timestamp", timestamp.ToInternalValue());
 
+  base::AutoLock guard(lock_);
+
   if (oracle_.CompleteCapture(frame_number, success, &timestamp)) {
     TRACE_EVENT_INSTANT0("gpu.capture", "CaptureSucceeded",
                          TRACE_EVENT_SCOPE_THREAD);
diff --git a/media/capture/content/thread_safe_capture_oracle.h b/media/capture/content/thread_safe_capture_oracle.h
index 921c6d1f..5e3283a7 100644
--- a/media/capture/content/thread_safe_capture_oracle.h
+++ b/media/capture/content/thread_safe_capture_oracle.h
@@ -42,12 +42,27 @@
                               base::TimeTicks timestamp,
                               bool success)> CaptureFrameCallback;
 
+  // Record a change |event| along with its |damage_rect| and |event_time|, and
+  // then make a decision whether to proceed with capture. The decision is based
+  // on recent event history, capture activity, and the availability of
+  // resources.
+  //
+  // If this method returns false, the caller should take no further action.
+  // Otherwise, |storage| is set to the destination for the video frame capture;
+  // and, the caller should initiate capture, and then run |callback| once the
+  // video frame has been populated with its content.
   bool ObserveEventAndDecideCapture(VideoCaptureOracle::Event event,
                                     const gfx::Rect& damage_rect,
                                     base::TimeTicks event_time,
                                     scoped_refptr<VideoFrame>* storage,
                                     CaptureFrameCallback* callback);
 
+  // Attempt to re-send the last frame to the VideoCaptureDevice::Client.
+  // Returns true if successful. This can fail if the last frame is no longer
+  // available in the buffer pool, or if the VideoCaptureOracle decides to
+  // reject the "passive" refresh.
+  bool AttemptPassiveRefresh();
+
   base::TimeDelta min_capture_period() const {
     return oracle_.min_capture_period();
   }
diff --git a/media/capture/content/video_capture_oracle.cc b/media/capture/content/video_capture_oracle.cc
index a363987d..e8dd752 100644
--- a/media/capture/content/video_capture_oracle.cc
+++ b/media/capture/content/video_capture_oracle.cc
@@ -14,16 +14,13 @@
 
 namespace {
 
-// This value controls how many redundant, timer-base captures occur when the
-// content is static. Redundantly capturing the same frame allows iterative
-// quality enhancement, and also allows the buffer to fill in "buffered mode".
-//
-// TODO(nick): Controlling this here is a hack and a layering violation, since
-// it's a strategy specific to the WebRTC consumer, and probably just papers
-// over some frame dropping and quality bugs. It should either be controlled at
-// a higher level, or else redundant frame generation should be pushed down
-// further into the WebRTC encoding stack.
-const int kNumRedundantCapturesOfStaticContent = 200;
+// When a non-compositor event arrives after animation has halted, this
+// controls how much time must elapse before deciding to allow a capture.
+const int kAnimationHaltPeriodBeforeOtherSamplingMicros = 250000;
+
+// When estimating frame durations, this is the hard upper-bound on the
+// estimate.
+const int kUpperBoundDurationEstimateMicros = 1000000;  // 1 second
 
 // The half-life of data points provided to the accumulator used when evaluating
 // the recent utilization of the buffer pool.  This value is based on a
@@ -106,8 +103,7 @@
       next_frame_number_(0),
       last_successfully_delivered_frame_number_(-1),
       num_frames_pending_(0),
-      smoothing_sampler_(min_capture_period,
-                         kNumRedundantCapturesOfStaticContent),
+      smoothing_sampler_(min_capture_period),
       content_sampler_(min_capture_period),
       resolution_chooser_(max_frame_size, resolution_change_policy),
       buffer_pool_utilization_(base::TimeDelta::FromMicroseconds(
@@ -164,20 +160,21 @@
       break;
     }
 
-    case kTimerPoll:
-      // While the timer is firing, only allow a sampling if there are none
-      // currently in-progress.
-      if (num_frames_pending_ == 0)
-        should_sample = smoothing_sampler_.IsOverdueForSamplingAt(event_time);
-      break;
-
+    case kActiveRefreshRequest:
+    case kPassiveRefreshRequest:
     case kMouseCursorUpdate:
-      // Only allow a sampling if there are none currently in-progress.
+      // Only allow non-compositor samplings when content has not recently been
+      // animating, and only if there are no samplings currently in progress.
       if (num_frames_pending_ == 0) {
-        smoothing_sampler_.ConsiderPresentationEvent(event_time);
-        should_sample = smoothing_sampler_.ShouldSample();
+        if (!content_sampler_.HasProposal() ||
+            ((event_time - last_time_animation_was_detected_).InMicroseconds() >
+             kAnimationHaltPeriodBeforeOtherSamplingMicros)) {
+          smoothing_sampler_.ConsiderPresentationEvent(event_time);
+          should_sample = smoothing_sampler_.ShouldSample();
+        }
       }
       break;
+
     case kNumEvents:
       NOTREACHED();
       break;
@@ -193,8 +190,8 @@
       duration_of_next_frame_ =
           event_time - GetFrameTimestamp(next_frame_number_ - 1);
     }
-    const base::TimeDelta upper_bound = base::TimeDelta::FromMilliseconds(
-        SmoothEventSampler::OVERDUE_DIRTY_THRESHOLD_MILLIS);
+    const base::TimeDelta upper_bound =
+        base::TimeDelta::FromMilliseconds(kUpperBoundDurationEstimateMicros);
     duration_of_next_frame_ =
         std::max(std::min(duration_of_next_frame_, upper_bound),
                  smoothing_sampler_.min_capture_period());
@@ -340,6 +337,24 @@
   estimated_capable_area_.Update(area_at_full_utilization, timestamp);
 }
 
+// static
+const char* VideoCaptureOracle::EventAsString(Event event) {
+  switch (event) {
+    case kCompositorUpdate:
+      return "compositor";
+    case kActiveRefreshRequest:
+      return "active_refresh";
+    case kPassiveRefreshRequest:
+      return "passive_refresh";
+    case kMouseCursorUpdate:
+      return "mouse";
+    case kNumEvents:
+      break;
+  }
+  NOTREACHED();
+  return "unknown";
+}
+
 base::TimeTicks VideoCaptureOracle::GetFrameTimestamp(int frame_number) const {
   DCHECK(IsFrameInRecentHistory(frame_number));
   return frame_timestamps_[frame_number % kMaxFrameTimestamps];
diff --git a/media/capture/content/video_capture_oracle.h b/media/capture/content/video_capture_oracle.h
index 8c4f6827..92a63a45 100644
--- a/media/capture/content/video_capture_oracle.h
+++ b/media/capture/content/video_capture_oracle.h
@@ -24,19 +24,13 @@
 class MEDIA_EXPORT VideoCaptureOracle {
  public:
   enum Event {
-    kTimerPoll,
     kCompositorUpdate,
+    kActiveRefreshRequest,
+    kPassiveRefreshRequest,
     kMouseCursorUpdate,
     kNumEvents,
   };
 
-  enum {
-    // The recommended minimum amount of time between calls to
-    // ObserveEventAndDecideCapture() for the kTimerPoll Event type.  Anything
-    // lower than this isn't harmful, just wasteful.
-    kMinTimerPollPeriodMillis = 125,  // 8 FPS
-  };
-
   VideoCaptureOracle(base::TimeDelta min_capture_period,
                      const gfx::Size& max_frame_size,
                      media::ResolutionChangePolicy resolution_change_policy,
@@ -104,6 +98,10 @@
     return last_time_animation_was_detected_;
   }
 
+  // Returns a NUL-terminated string containing a short, human-readable form of
+  // |event|.
+  static const char* EventAsString(Event event);
+
  private:
   // Retrieve/Assign a frame timestamp by capture |frame_number|.  Only valid
   // when IsFrameInRecentHistory(frame_number) returns true.
diff --git a/media/capture/content/video_capture_oracle_unittest.cc b/media/capture/content/video_capture_oracle_unittest.cc
index 64fff4f..dbfcae2 100644
--- a/media/capture/content/video_capture_oracle_unittest.cc
+++ b/media/capture/content/video_capture_oracle_unittest.cc
@@ -198,12 +198,12 @@
   }
 }
 
-// Tests that VideoCaptureOracle prevents timer polling from initiating
+// Tests that VideoCaptureOracle prevents refresh request events from initiating
 // simultaneous captures.
-TEST(VideoCaptureOracleTest, SamplesOnlyOneOverdueFrameAtATime) {
+TEST(VideoCaptureOracleTest, SamplesAtCorrectTimesAroundRefreshRequests) {
   const base::TimeDelta vsync_interval = base::TimeDelta::FromSeconds(1) / 60;
-  const base::TimeDelta timer_interval = base::TimeDelta::FromMilliseconds(
-      VideoCaptureOracle::kMinTimerPollPeriodMillis);
+  const base::TimeDelta refresh_interval =
+      base::TimeDelta::FromMilliseconds(125);  // 8 FPS
 
   VideoCaptureOracle oracle(Get30HzPeriod(), Get720pSize(),
                             media::RESOLUTION_POLICY_FIXED_RESOLUTION, false);
@@ -236,24 +236,24 @@
   }
   int frame_number = oracle.RecordCapture(0.0);
 
-  // Stop providing the compositor events and start providing timer polling
+  // Stop providing the compositor events and start providing refresh request
   // events.  No overdue samplings should be recommended because of the
   // not-yet-complete compositor-based capture.
   for (int i = 0; i < 10; ++i) {
-    t += timer_interval;
+    t += refresh_interval;
     ASSERT_FALSE(oracle.ObserveEventAndDecideCapture(
-        VideoCaptureOracle::kTimerPoll, gfx::Rect(), t));
+        VideoCaptureOracle::kPassiveRefreshRequest, gfx::Rect(), t));
   }
 
   // Now, complete the oustanding compositor-based capture and continue
-  // providing timer polling events.  The oracle should start recommending
+  // providing refresh request events.  The oracle should start recommending
   // sampling again.
   ASSERT_TRUE(oracle.CompleteCapture(frame_number, true, &ignored));
   did_complete_a_capture = false;
   for (int i = 0; i < 10; ++i) {
-    t += timer_interval;
-    if (oracle.ObserveEventAndDecideCapture(VideoCaptureOracle::kTimerPoll,
-                                            gfx::Rect(), t)) {
+    t += refresh_interval;
+    if (oracle.ObserveEventAndDecideCapture(
+            VideoCaptureOracle::kPassiveRefreshRequest, gfx::Rect(), t)) {
       ASSERT_TRUE(
           oracle.CompleteCapture(oracle.RecordCapture(0.0), true, &ignored));
       did_complete_a_capture = true;
@@ -261,30 +261,30 @@
   }
   ASSERT_TRUE(did_complete_a_capture);
 
-  // Start one more timer-based capture, but do not notify of completion yet.
+  // Start one more "refresh" capture, but do not notify of completion yet.
   for (int i = 0; i <= 10; ++i) {
     ASSERT_GT(10, i) << "BUG: Seems like it'll never happen!";
-    t += timer_interval;
-    if (oracle.ObserveEventAndDecideCapture(VideoCaptureOracle::kTimerPoll,
-                                            gfx::Rect(), t)) {
+    t += refresh_interval;
+    if (oracle.ObserveEventAndDecideCapture(
+            VideoCaptureOracle::kPassiveRefreshRequest, gfx::Rect(), t)) {
       break;
     }
   }
   frame_number = oracle.RecordCapture(0.0);
 
   // Confirm that the oracle does not recommend sampling until the outstanding
-  // timer-based capture completes.
+  // "refresh" capture completes.
   for (int i = 0; i < 10; ++i) {
-    t += timer_interval;
+    t += refresh_interval;
     ASSERT_FALSE(oracle.ObserveEventAndDecideCapture(
-        VideoCaptureOracle::kTimerPoll, gfx::Rect(), t));
+        VideoCaptureOracle::kPassiveRefreshRequest, gfx::Rect(), t));
   }
   ASSERT_TRUE(oracle.CompleteCapture(frame_number, true, &ignored));
   for (int i = 0; i <= 10; ++i) {
     ASSERT_GT(10, i) << "BUG: Seems like it'll never happen!";
-    t += timer_interval;
-    if (oracle.ObserveEventAndDecideCapture(VideoCaptureOracle::kTimerPoll,
-                                            gfx::Rect(), t)) {
+    t += refresh_interval;
+    if (oracle.ObserveEventAndDecideCapture(
+            VideoCaptureOracle::kPassiveRefreshRequest, gfx::Rect(), t)) {
       break;
     }
   }
diff --git a/mojo/edk/embedder/embedder.h b/mojo/edk/embedder/embedder.h
index 3eadc36..6a9b305 100644
--- a/mojo/edk/embedder/embedder.h
+++ b/mojo/edk/embedder/embedder.h
@@ -94,8 +94,6 @@
 // |read_only| is whether the handle is a read-only handle to shared memory.
 // This |MojoHandle| is a Mojo shared buffer and can be manipulated using the
 // shared buffer functions and transferred over a message pipe.
-// TODO(crbug.com/556587): Support read-only handles. Currently, |read_only|
-// must be false.
 MOJO_SYSTEM_IMPL_EXPORT MojoResult
 CreateSharedBufferWrapper(base::SharedMemoryHandle shared_memory_handle,
                           size_t num_bytes,
@@ -109,8 +107,6 @@
 // Note: The value of |shared_memory_handle| may be
 // base::SharedMemory::NULLHandle(), even if this function returns success.
 // Callers should perform appropriate checks.
-// TODO(crbug.com/556587): Support read-only handles. Currently, |read_only|
-// will always return |false|.
 MOJO_SYSTEM_IMPL_EXPORT MojoResult
 PassSharedMemoryHandle(MojoHandle mojo_handle,
                        base::SharedMemoryHandle* shared_memory_handle,
diff --git a/mojo/edk/embedder/platform_shared_buffer.cc b/mojo/edk/embedder/platform_shared_buffer.cc
index 614b19c..a29a7abd 100644
--- a/mojo/edk/embedder/platform_shared_buffer.cc
+++ b/mojo/edk/embedder/platform_shared_buffer.cc
@@ -44,7 +44,7 @@
 PlatformSharedBuffer* PlatformSharedBuffer::Create(size_t num_bytes) {
   DCHECK_GT(num_bytes, 0u);
 
-  PlatformSharedBuffer* rv = new PlatformSharedBuffer(num_bytes);
+  PlatformSharedBuffer* rv = new PlatformSharedBuffer(num_bytes, false);
   if (!rv->Init()) {
     // We can't just delete it directly, due to the "in destructor" (debug)
     // check.
@@ -58,10 +58,11 @@
 // static
 PlatformSharedBuffer* PlatformSharedBuffer::CreateFromPlatformHandle(
     size_t num_bytes,
+    bool read_only,
     ScopedPlatformHandle platform_handle) {
   DCHECK_GT(num_bytes, 0u);
 
-  PlatformSharedBuffer* rv = new PlatformSharedBuffer(num_bytes);
+  PlatformSharedBuffer* rv = new PlatformSharedBuffer(num_bytes, read_only);
   if (!rv->InitFromPlatformHandle(std::move(platform_handle))) {
     // We can't just delete it directly, due to the "in destructor" (debug)
     // check.
@@ -78,9 +79,8 @@
     bool read_only,
     base::SharedMemoryHandle handle) {
   DCHECK_GT(num_bytes, 0u);
-  DCHECK(!read_only);
 
-  PlatformSharedBuffer* rv = new PlatformSharedBuffer(num_bytes);
+  PlatformSharedBuffer* rv = new PlatformSharedBuffer(num_bytes, read_only);
   rv->InitFromSharedMemoryHandle(handle);
 
   return rv;
@@ -90,6 +90,10 @@
   return num_bytes_;
 }
 
+bool PlatformSharedBuffer::IsReadOnly() const {
+    return read_only_;
+}
+
 scoped_ptr<PlatformSharedBufferMapping> PlatformSharedBuffer::Map(
     size_t offset,
     size_t length) {
@@ -125,7 +129,7 @@
     return nullptr;
 
   scoped_ptr<PlatformSharedBufferMapping> mapping(
-      new PlatformSharedBufferMapping(handle, offset, length));
+      new PlatformSharedBufferMapping(handle, read_only_, offset, length));
   if (mapping->Map())
     return make_scoped_ptr(mapping.release());
 
@@ -164,16 +168,34 @@
   return base::SharedMemory::DuplicateHandle(shared_memory_->handle());
 }
 
-PlatformSharedBuffer::PlatformSharedBuffer(size_t num_bytes)
-    : num_bytes_(num_bytes) {}
+PlatformSharedBuffer* PlatformSharedBuffer::CreateReadOnlyDuplicate() {
+  DCHECK(shared_memory_);
+  base::SharedMemoryHandle handle;
+  bool success;
+  {
+    base::AutoLock locker(lock_);
+    success = shared_memory_->ShareReadOnlyToProcess(
+        base::GetCurrentProcessHandle(), &handle);
+  }
+  if (!success || handle == base::SharedMemory::NULLHandle())
+      return nullptr;
+
+  return CreateFromSharedMemoryHandle(num_bytes_, true, handle);
+}
+
+PlatformSharedBuffer::PlatformSharedBuffer(size_t num_bytes, bool read_only)
+    : num_bytes_(num_bytes), read_only_(read_only) {}
 
 PlatformSharedBuffer::~PlatformSharedBuffer() {}
 
 bool PlatformSharedBuffer::Init() {
   DCHECK(!shared_memory_);
+  DCHECK(!read_only_);
 
   base::SharedMemoryCreateOptions options;
   options.size = num_bytes_;
+  // By default, we can share as read-only.
+  options.share_read_only = true;
 #if defined(OS_MACOSX) && !defined(OS_IOS)
   options.type = base::SharedMemoryHandle::MACH;
 #endif
@@ -201,7 +223,7 @@
   base::SharedMemoryHandle handle(platform_handle.release().handle, false);
 #endif
 
-  shared_memory_.reset(new base::SharedMemory(handle, false));
+  shared_memory_.reset(new base::SharedMemory(handle, read_only_));
   return true;
 }
 
@@ -209,8 +231,7 @@
     base::SharedMemoryHandle handle) {
   DCHECK(!shared_memory_);
 
-  // TODO(crbug.com/556587): Support read-only handles.
-  shared_memory_.reset(new base::SharedMemory(handle, false));
+  shared_memory_.reset(new base::SharedMemory(handle, read_only_));
 }
 
 PlatformSharedBufferMapping::~PlatformSharedBufferMapping() {
diff --git a/mojo/edk/embedder/platform_shared_buffer.h b/mojo/edk/embedder/platform_shared_buffer.h
index dfe91651..1cfcd3a 100644
--- a/mojo/edk/embedder/platform_shared_buffer.h
+++ b/mojo/edk/embedder/platform_shared_buffer.h
@@ -31,9 +31,6 @@
 //   - Sizes/offsets (of the shared memory and mappings) are arbitrary, and not
 //     restricted by page size. However, more memory may actually be mapped than
 //     requested.
-//
-// It currently does NOT support the following:
-//   - Sharing read-only. (This will probably eventually be supported.)
 class MOJO_SYSTEM_IMPL_EXPORT PlatformSharedBuffer
     : public base::RefCountedThreadSafe<PlatformSharedBuffer> {
  public:
@@ -45,6 +42,7 @@
   // handle |platform_handle|. Returns null on failure.
   static PlatformSharedBuffer* CreateFromPlatformHandle(
       size_t num_bytes,
+      bool read_only,
       ScopedPlatformHandle platform_handle);
 
   // Creates a shared buffer of size |num_bytes| from the existing shared memory
@@ -57,6 +55,9 @@
   // Gets the size of shared buffer (in number of bytes).
   size_t GetNumBytes() const;
 
+  // Returns whether this shared buffer is read-only.
+  bool IsReadOnly() const;
+
   // Maps (some) of the shared buffer into memory; [|offset|, |offset + length|]
   // must be contained in [0, |num_bytes|], and |length| must be at least 1.
   // Returns null on failure.
@@ -71,7 +72,6 @@
                                                      size_t length);
 
   // Duplicates the underlying platform handle and passes it to the caller.
-  // TODO(vtl): On POSIX, we'll need two FDs to support sharing read-only.
   ScopedPlatformHandle DuplicatePlatformHandle();
 
   // Duplicates the underlying shared memory handle and passes it to the caller.
@@ -83,10 +83,15 @@
   // be disposed of.
   ScopedPlatformHandle PassPlatformHandle();
 
+  // Create and return a read-only duplicate of this shared buffer. If this
+  // shared buffer isn't capable of returning a read-only duplicate, then
+  // nullptr will be returned.
+  PlatformSharedBuffer* CreateReadOnlyDuplicate();
+
  private:
   friend class base::RefCountedThreadSafe<PlatformSharedBuffer>;
 
-  explicit PlatformSharedBuffer(size_t num_bytes);
+  PlatformSharedBuffer(size_t num_bytes, bool read_only);
   ~PlatformSharedBuffer();
 
   // This is called by |Create()| before this object is given to anyone.
@@ -100,6 +105,7 @@
   void InitFromSharedMemoryHandle(base::SharedMemoryHandle handle);
 
   const size_t num_bytes_;
+  const bool read_only_;
 
   base::Lock lock_;
   scoped_ptr<base::SharedMemory> shared_memory_;
@@ -126,12 +132,13 @@
   friend class PlatformSharedBuffer;
 
   PlatformSharedBufferMapping(base::SharedMemoryHandle handle,
+                              bool read_only,
                               size_t offset,
                               size_t length)
       : offset_(offset),
         length_(length),
         base_(nullptr),
-        shared_memory_(handle, false) {}
+        shared_memory_(handle, read_only) {}
 
   bool Map();
   void Unmap();
diff --git a/mojo/edk/system/broker_posix.cc b/mojo/edk/system/broker_posix.cc
index 91b9cb5..3cbb953 100644
--- a/mojo/edk/system/broker_posix.cc
+++ b/mojo/edk/system/broker_posix.cc
@@ -112,7 +112,8 @@
                            BrokerMessageType::BUFFER_RESPONSE, 1,
                            &incoming_platform_handles)) {
     return PlatformSharedBuffer::CreateFromPlatformHandle(
-        num_bytes, ScopedPlatformHandle(incoming_platform_handles.front()));
+        num_bytes, false /* read_only */,
+        ScopedPlatformHandle(incoming_platform_handles.front()));
   }
 
   return nullptr;
diff --git a/mojo/edk/system/core.cc b/mojo/edk/system/core.cc
index ca6105d..b3602d7 100644
--- a/mojo/edk/system/core.cc
+++ b/mojo/edk/system/core.cc
@@ -160,7 +160,6 @@
     bool read_only,
     MojoHandle* mojo_wrapper_handle) {
   DCHECK(num_bytes);
-  CHECK(!read_only);
   scoped_refptr<PlatformSharedBuffer> platform_buffer =
       PlatformSharedBuffer::CreateFromSharedMemoryHandle(num_bytes, read_only,
                                                          shared_memory_handle);
@@ -214,7 +213,7 @@
   if (num_bytes)
     *num_bytes = platform_shared_buffer->GetNumBytes();
   if (read_only)
-    *read_only = false;
+    *read_only = platform_shared_buffer->IsReadOnly();
   *shared_memory_handle = platform_shared_buffer->DuplicateSharedMemoryHandle();
 
   shm_dispatcher->Close();
diff --git a/mojo/edk/system/data_pipe_consumer_dispatcher.cc b/mojo/edk/system/data_pipe_consumer_dispatcher.cc
index f978f949..7bf0b01 100644
--- a/mojo/edk/system/data_pipe_consumer_dispatcher.cc
+++ b/mojo/edk/system/data_pipe_consumer_dispatcher.cc
@@ -403,6 +403,7 @@
   scoped_refptr<PlatformSharedBuffer> ring_buffer =
       PlatformSharedBuffer::CreateFromPlatformHandle(
           state->options.capacity_num_bytes,
+          false /* read_only */,
           ScopedPlatformHandle(buffer_handle));
   if (!ring_buffer) {
     DLOG(ERROR) << "Failed to deserialize shared buffer handle.";
diff --git a/mojo/edk/system/data_pipe_producer_dispatcher.cc b/mojo/edk/system/data_pipe_producer_dispatcher.cc
index d8d8abf1..d3b2530 100644
--- a/mojo/edk/system/data_pipe_producer_dispatcher.cc
+++ b/mojo/edk/system/data_pipe_producer_dispatcher.cc
@@ -385,6 +385,7 @@
   scoped_refptr<PlatformSharedBuffer> ring_buffer =
       PlatformSharedBuffer::CreateFromPlatformHandle(
           state->options.capacity_num_bytes,
+          false /* read_only */,
           ScopedPlatformHandle(buffer_handle));
   if (!ring_buffer) {
     DLOG(ERROR) << "Failed to deserialize shared buffer handle.";
diff --git a/mojo/edk/system/shared_buffer_dispatcher.cc b/mojo/edk/system/shared_buffer_dispatcher.cc
index 4c548e0c..d531989c 100644
--- a/mojo/edk/system/shared_buffer_dispatcher.cc
+++ b/mojo/edk/system/shared_buffer_dispatcher.cc
@@ -26,8 +26,12 @@
 
 struct SerializedState {
   uint64_t num_bytes;
+  uint32_t flags;
+  uint32_t padding;
 };
 
+const uint32_t kSerializedStateFlagsReadOnly = 1 << 0;
+
 #pragma pack(pop)
 
 static_assert(sizeof(SerializedState) % 8 == 0,
@@ -141,9 +145,10 @@
 
   // Wrapping |platform_handle| in a |ScopedPlatformHandle| means that it'll be
   // closed even if creation fails.
+  bool read_only = (serialization->flags & kSerializedStateFlagsReadOnly);
   scoped_refptr<PlatformSharedBuffer> shared_buffer(
       PlatformSharedBuffer::CreateFromPlatformHandle(
-          static_cast<size_t>(serialization->num_bytes),
+          static_cast<size_t>(serialization->num_bytes), read_only,
           ScopedPlatformHandle(platform_handle)));
   if (!shared_buffer) {
     LOG(ERROR)
@@ -190,6 +195,21 @@
   base::AutoLock lock(lock_);
   if (in_transit_)
     return MOJO_RESULT_INVALID_ARGUMENT;
+
+  if ((validated_options.flags &
+       MOJO_DUPLICATE_BUFFER_HANDLE_OPTIONS_FLAG_READ_ONLY) &&
+      (!shared_buffer_->IsReadOnly())) {
+    // If a read-only duplicate is requested and |shared_buffer_| is not
+    // read-only, make a read-only duplicate of |shared_buffer_|.
+    scoped_refptr<PlatformSharedBuffer> read_only_buffer =
+        shared_buffer_->CreateReadOnlyDuplicate();
+    if (!read_only_buffer)
+      return MOJO_RESULT_FAILED_PRECONDITION;
+    DCHECK(read_only_buffer->IsReadOnly());
+    *new_dispatcher = CreateInternal(std::move(read_only_buffer));
+    return MOJO_RESULT_OK;
+  }
+
   *new_dispatcher = CreateInternal(shared_buffer_);
   return MOJO_RESULT_OK;
 }
@@ -215,8 +235,10 @@
   DCHECK(mapping);
   *mapping = shared_buffer_->MapNoCheck(static_cast<size_t>(offset),
                                         static_cast<size_t>(num_bytes));
-  if (!*mapping)
+  if (!*mapping) {
+    LOG(ERROR) << "Unable to map: read_only" << shared_buffer_->IsReadOnly();
     return MOJO_RESULT_RESOURCE_EXHAUSTED;
+  }
 
   return MOJO_RESULT_OK;
 }
@@ -237,6 +259,9 @@
   base::AutoLock lock(lock_);
   serialization->num_bytes =
         static_cast<uint64_t>(shared_buffer_->GetNumBytes());
+  serialization->flags =
+      (shared_buffer_->IsReadOnly() ? kSerializedStateFlagsReadOnly : 0);
+  serialization->padding = 0;
 
   handle_for_transit_ = shared_buffer_->DuplicatePlatformHandle();
   if (!handle_for_transit_.is_valid()) {
@@ -283,7 +308,7 @@
     const MojoDuplicateBufferHandleOptions* in_options,
     MojoDuplicateBufferHandleOptions* out_options) {
   const MojoDuplicateBufferHandleOptionsFlags kKnownFlags =
-      MOJO_DUPLICATE_BUFFER_HANDLE_OPTIONS_FLAG_NONE;
+      MOJO_DUPLICATE_BUFFER_HANDLE_OPTIONS_FLAG_READ_ONLY;
   static const MojoDuplicateBufferHandleOptions kDefaultOptions = {
       static_cast<uint32_t>(sizeof(MojoDuplicateBufferHandleOptions)),
       MOJO_DUPLICATE_BUFFER_HANDLE_OPTIONS_FLAG_NONE};
diff --git a/mojo/edk/system/shared_buffer_dispatcher_unittest.cc b/mojo/edk/system/shared_buffer_dispatcher_unittest.cc
index 5605264..6e26bf9f 100644
--- a/mojo/edk/system/shared_buffer_dispatcher_unittest.cc
+++ b/mojo/edk/system/shared_buffer_dispatcher_unittest.cc
@@ -220,6 +220,8 @@
   MojoDuplicateBufferHandleOptions options[] = {
       {sizeof(MojoDuplicateBufferHandleOptions),
        MOJO_DUPLICATE_BUFFER_HANDLE_OPTIONS_FLAG_NONE},
+      {sizeof(MojoDuplicateBufferHandleOptions),
+       MOJO_DUPLICATE_BUFFER_HANDLE_OPTIONS_FLAG_READ_ONLY},
       {sizeof(MojoDuplicateBufferHandleOptionsFlags), ~0u}};
   for (size_t i = 0; i < arraysize(options); i++) {
     scoped_refptr<Dispatcher> dispatcher2;
@@ -227,6 +229,10 @@
                                   &options[i], &dispatcher2));
     ASSERT_TRUE(dispatcher2);
     EXPECT_EQ(Dispatcher::Type::SHARED_BUFFER, dispatcher2->GetType());
+    {
+      scoped_ptr<PlatformSharedBufferMapping> mapping;
+      EXPECT_EQ(MOJO_RESULT_OK, dispatcher2->MapBuffer(0, 100, 0, &mapping));
+    }
     EXPECT_EQ(MOJO_RESULT_OK, dispatcher2->Close());
   }
 
diff --git a/mojo/edk/system/shared_buffer_unittest.cc b/mojo/edk/system/shared_buffer_unittest.cc
index 210c2f55..9451ae8 100644
--- a/mojo/edk/system/shared_buffer_unittest.cc
+++ b/mojo/edk/system/shared_buffer_unittest.cc
@@ -8,6 +8,7 @@
 #include <utility>
 
 #include "base/logging.h"
+#include "base/memory/shared_memory.h"
 #include "base/strings/string_piece.h"
 #include "mojo/edk/test/mojo_test_base.h"
 #include "mojo/public/c/system/types.h"
@@ -31,7 +32,7 @@
   MojoHandle h = CreateBuffer(message.size());
   WriteToBuffer(h, 0, message);
 
-  MojoHandle dupe = DuplicateBuffer(h);
+  MojoHandle dupe = DuplicateBuffer(h, false);
   ExpectBufferContents(dupe, 0, message);
 }
 
@@ -40,7 +41,7 @@
   MojoHandle h = CreateBuffer(message.size());
   WriteToBuffer(h, 0, message);
 
-  MojoHandle dupe = DuplicateBuffer(h);
+  MojoHandle dupe = DuplicateBuffer(h, false);
   MojoHandle p0, p1;
   CreateMessagePipe(&p0, &p1);
 
@@ -73,7 +74,7 @@
   MojoHandle b = CreateBuffer(message.size());
 
   RUN_CHILD_ON_PIPE(CopyToBufferClient, h)
-    MojoHandle dupe = DuplicateBuffer(b);
+    MojoHandle dupe = DuplicateBuffer(b, false);
     WriteMessageWithHandles(h, message, &dupe, 1);
     WriteMessage(h, "quit");
   END_CHILD()
@@ -120,7 +121,7 @@
   MojoHandle b = CreateBuffer(message.size());
 
   // Send a copy of the buffer to the parent and the other child.
-  MojoHandle dupe = DuplicateBuffer(b);
+  MojoHandle dupe = DuplicateBuffer(b, false);
   WriteMessageWithHandles(h, "", &b, 1);
   WriteMessageWithHandles(other_child, "", &dupe, 1);
 
@@ -254,6 +255,93 @@
   ExpectBufferContents(b, 0, message);
 }
 
+DEFINE_TEST_CLIENT_TEST_WITH_PIPE(ReadAndMapWriteSharedBuffer,
+                                  SharedBufferTest, h) {
+  // Receive the shared buffer.
+  MojoHandle b;
+  EXPECT_EQ("hello", ReadMessageWithHandles(h, &b, 1));
+
+  // Read from the bufer.
+  ExpectBufferContents(b, 0, "hello");
+
+  // Extract the shared memory handle and try to map it writable.
+  base::SharedMemoryHandle shm_handle;
+  bool read_only = false;
+  ASSERT_EQ(MOJO_RESULT_OK,
+            PassSharedMemoryHandle(b, &shm_handle, nullptr, &read_only));
+  base::SharedMemory shared_memory(shm_handle, false);
+  EXPECT_TRUE(read_only);
+  EXPECT_FALSE(shared_memory.Map(1234));
+
+  EXPECT_EQ("quit", ReadMessage(h));
+  WriteMessage(h, "ok");
+}
+
+#if defined(OS_ANDROID)
+// Android multi-process tests are not executing the new process. This is flaky.
+#define MAYBE_CreateAndPassReadOnlyBuffer DISABLED_CreateAndPassReadOnlyBuffer
+#else
+#define MAYBE_CreateAndPassReadOnlyBuffer CreateAndPassReadOnlyBuffer
+#endif
+TEST_F(SharedBufferTest, MAYBE_CreateAndPassReadOnlyBuffer) {
+  RUN_CHILD_ON_PIPE(ReadAndMapWriteSharedBuffer, h)
+    // Create a new shared buffer.
+    MojoHandle b = CreateBuffer(1234);
+    WriteToBuffer(b, 0, "hello");
+
+    // Send a read-only copy of the buffer to the child.
+    MojoHandle dupe = DuplicateBuffer(b, true /* read_only */);
+    WriteMessageWithHandles(h, "hello", &dupe, 1);
+
+    WriteMessage(h, "quit");
+    EXPECT_EQ("ok", ReadMessage(h));
+  END_CHILD()
+}
+
+DEFINE_TEST_CLIENT_TEST_WITH_PIPE(CreateAndPassReadOnlyBuffer,
+                                  SharedBufferTest, h) {
+  // Create a new shared buffer.
+  MojoHandle b = CreateBuffer(1234);
+  WriteToBuffer(b, 0, "hello");
+
+  // Send a read-only copy of the buffer to the parent.
+  MojoHandle dupe = DuplicateBuffer(b, true /* read_only */);
+  WriteMessageWithHandles(h, "", &dupe, 1);
+
+  EXPECT_EQ("quit", ReadMessage(h));
+  WriteMessage(h, "ok");
+}
+
+#if defined(OS_ANDROID) || (defined(OS_POSIX) && !defined(OS_MACOSX))
+// Android multi-process tests are not executing the new process. This is flaky.
+// Non-OSX posix uses a sync broker to create shared memory. Creating read-only
+// duplicates in child processes is not currently supported via the sync broker.
+#define MAYBE_CreateAndPassFromChildReadOnlyBuffer \
+    DISABLED_CreateAndPassFromChildReadOnlyBuffer
+#else
+#define MAYBE_CreateAndPassFromChildReadOnlyBuffer \
+    CreateAndPassFromChildReadOnlyBuffer
+#endif
+TEST_F(SharedBufferTest, MAYBE_CreateAndPassFromChildReadOnlyBuffer) {
+  RUN_CHILD_ON_PIPE(CreateAndPassReadOnlyBuffer, h)
+    MojoHandle b;
+    EXPECT_EQ("", ReadMessageWithHandles(h, &b, 1));
+    ExpectBufferContents(b, 0, "hello");
+
+    // Extract the shared memory handle and try to map it writable.
+    base::SharedMemoryHandle shm_handle;
+    bool read_only = false;
+    ASSERT_EQ(MOJO_RESULT_OK,
+              PassSharedMemoryHandle(b, &shm_handle, nullptr, &read_only));
+    base::SharedMemory shared_memory(shm_handle, false);
+    EXPECT_TRUE(read_only);
+    EXPECT_FALSE(shared_memory.Map(1234));
+
+    WriteMessage(h, "quit");
+    EXPECT_EQ("ok", ReadMessage(h));
+  END_CHILD()
+}
+
 #endif  // !defined(OS_IOS)
 
 }  // namespace
diff --git a/mojo/edk/test/mojo_test_base.cc b/mojo/edk/test/mojo_test_base.cc
index 4b044f6..b9b6860 100644
--- a/mojo/edk/test/mojo_test_base.cc
+++ b/mojo/edk/test/mojo_test_base.cc
@@ -224,10 +224,16 @@
 }
 
 // static
-MojoHandle MojoTestBase::DuplicateBuffer(MojoHandle h) {
+MojoHandle MojoTestBase::DuplicateBuffer(MojoHandle h, bool read_only) {
   MojoHandle new_handle;
+  MojoDuplicateBufferHandleOptions options = {
+    sizeof(MojoDuplicateBufferHandleOptions),
+    MOJO_DUPLICATE_BUFFER_HANDLE_OPTIONS_FLAG_NONE
+  };
+  if (read_only)
+    options.flags |= MOJO_DUPLICATE_BUFFER_HANDLE_OPTIONS_FLAG_READ_ONLY;
   EXPECT_EQ(MOJO_RESULT_OK,
-            MojoDuplicateBufferHandle(h, nullptr, &new_handle));
+            MojoDuplicateBufferHandle(h, &options, &new_handle));
   return new_handle;
 }
 
diff --git a/mojo/edk/test/mojo_test_base.h b/mojo/edk/test/mojo_test_base.h
index 1dcadf1..0bae238 100644
--- a/mojo/edk/test/mojo_test_base.h
+++ b/mojo/edk/test/mojo_test_base.h
@@ -115,7 +115,7 @@
   static MojoHandle CreateBuffer(uint64_t size);
 
   // Duplicates a shared buffer to a new handle.
-  static MojoHandle DuplicateBuffer(MojoHandle h);
+  static MojoHandle DuplicateBuffer(MojoHandle h, bool read_only);
 
   // Maps a buffer, writes some data into it, and unmaps it.
   static void WriteToBuffer(MojoHandle h,
diff --git a/mojo/public/c/system/buffer.h b/mojo/public/c/system/buffer.h
index 97f4de4..b6d905b7 100644
--- a/mojo/public/c/system/buffer.h
+++ b/mojo/public/c/system/buffer.h
@@ -56,6 +56,9 @@
 //   |MojoDuplicateBufferHandleOptionsFlags flags|: Reserved for future use.
 //       |MOJO_DUPLICATE_BUFFER_HANDLE_OPTIONS_FLAG_NONE|: No flags; default
 //       mode.
+//       |MOJO_DUPLICATE_BUFFER_HANDLE_OPTIONS_FLAG_READ_ONLY|: The duplicate
+//       shared buffer can only be mapped read-only. A read-only duplicate can
+//       only be created before the buffer is passed over a message pipe.
 //
 // TODO(vtl): Add flags to remove writability (and executability)? Also, COW?
 
@@ -64,6 +67,8 @@
 #ifdef __cplusplus
 const MojoDuplicateBufferHandleOptionsFlags
     MOJO_DUPLICATE_BUFFER_HANDLE_OPTIONS_FLAG_NONE = 0;
+const MojoDuplicateBufferHandleOptionsFlags
+    MOJO_DUPLICATE_BUFFER_HANDLE_OPTIONS_FLAG_READ_ONLY = 1 << 0;
 #else
 #define MOJO_DUPLICATE_BUFFER_HANDLE_OPTIONS_FLAG_NONE \
   ((MojoDuplicateBufferHandleOptionsFlags)0)
diff --git a/mojo/public/cpp/bindings/lib/array_serialization_traits.h b/mojo/public/cpp/bindings/lib/array_serialization_traits.h
index 5e0e5afe..17817e01 100644
--- a/mojo/public/cpp/bindings/lib/array_serialization_traits.h
+++ b/mojo/public/cpp/bindings/lib/array_serialization_traits.h
@@ -398,8 +398,8 @@
     for (size_t i = 0; i < input->size(); ++i) {
       // We don't short-circuit on failure since we can't know what the native
       // type's ParamTraits' expectations are.
-      success =
-          success && DeserializeNative_(input->at(i), &result[i], context);
+      if (!DeserializeNative_(input->at(i), &result[i], context))
+        success = false;
     }
     output->Swap(&result);
     return success;
diff --git a/net/test/embedded_test_server/http_request.cc b/net/test/embedded_test_server/http_request.cc
index 7d54326..a1332be 100644
--- a/net/test/embedded_test_server/http_request.cc
+++ b/net/test/embedded_test_server/http_request.cc
@@ -246,6 +246,8 @@
     return METHOD_PATCH;
   } else if (token == "connect") {
     return METHOD_CONNECT;
+  } else if (token == "options") {
+    return METHOD_OPTIONS;
   }
   LOG(WARNING) << "Method not implemented: " << token;
   return METHOD_GET;
diff --git a/net/test/embedded_test_server/http_request.h b/net/test/embedded_test_server/http_request.h
index 2a560b6..d9e54b8 100644
--- a/net/test/embedded_test_server/http_request.h
+++ b/net/test/embedded_test_server/http_request.h
@@ -32,6 +32,7 @@
   METHOD_DELETE,
   METHOD_PATCH,
   METHOD_CONNECT,
+  METHOD_OPTIONS,
 };
 
 // Represents a HTTP request. Since it can be big, use scoped_ptr to pass it
diff --git a/remoting/host/security_key/remote_security_key_main.cc b/remoting/host/security_key/remote_security_key_main.cc
index a13efb1..f7c11c2 100644
--- a/remoting/host/security_key/remote_security_key_main.cc
+++ b/remoting/host/security_key/remote_security_key_main.cc
@@ -4,12 +4,12 @@
 
 #include "remoting/host/security_key/remote_security_key_main.h"
 
+#include <memory>
 #include <string>
 #include <utility>
 
 #include "base/at_exit.h"
 #include "base/command_line.h"
-#include "base/memory/scoped_ptr.h"
 #include "base/message_loop/message_loop.h"
 #include "base/run_loop.h"
 #include "remoting/host/host_exit_codes.h"
@@ -48,7 +48,7 @@
 
   base::RunLoop run_loop;
 
-  scoped_ptr<RemoteSecurityKeyIpcClient> ipc_client(
+  std::unique_ptr<RemoteSecurityKeyIpcClient> ipc_client(
       new RemoteSecurityKeyIpcClient());
 
   RemoteSecurityKeyMessageHandler message_handler;
diff --git a/testing/android/junit/BUILD.gn b/testing/android/junit/BUILD.gn
index 080daaf..328f052 100644
--- a/testing/android/junit/BUILD.gn
+++ b/testing/android/junit/BUILD.gn
@@ -34,7 +34,7 @@
 }
 
 # GYP: //testing/android/junit_test.gyp:junit_unit_tests
-junit_binary("junit_unittests") {
+junit_binary("junit_unit_tests") {
   java_files = [
     "javatests/src/org/chromium/testing/local/GtestFilterTest.java",
     "javatests/src/org/chromium/testing/local/GtestLoggerTest.java",
diff --git a/third_party/WebKit/LayoutTests/TestExpectations b/third_party/WebKit/LayoutTests/TestExpectations
index 01041f8..c585913 100644
--- a/third_party/WebKit/LayoutTests/TestExpectations
+++ b/third_party/WebKit/LayoutTests/TestExpectations
@@ -108,6 +108,21 @@
 crbug.com/538697 [ Win7 Debug ] virtual/threaded/printing/webgl-oversized-printing.html [ Crash ]
 crbug.com/538697 [ Win7 Debug ] printing/webgl-oversized-printing.html [ Crash ]
 
+crbug.com/303728 [ Win10 ] printing/fixed-positioned-headers-and-footers-absolute-covering-some-pages.html [ Failure ]
+crbug.com/303728 [ Win10 ] virtual/threaded/printing/fixed-positioned-headers-and-footers-absolute-covering-some-pages.html [ Failure ]
+crbug.com/303728 [ Win10 ] printing/absolute-position-headers-and-footers.html [ Failure ]
+crbug.com/303728 [ Win10 ] printing/fixed-positioned-but-static-headers-and-footers.html [ Failure ]
+crbug.com/303728 [ Win10 ] printing/fixed-positioned-headers-and-footers-clipped.html [ Failure ]
+crbug.com/303728 [ Win10 ] printing/fixed-positioned-headers-and-footers-inside-transform.html [ Failure ]
+crbug.com/303728 [ Win10 ] printing/fixed-positioned-headers-and-footers-larger-than-page.html [ Failure ]
+crbug.com/303728 [ Win10 ] printing/fixed-positioned-headers-and-footers.html [ Failure ]
+crbug.com/303728 [ Win10 ] virtual/threaded/printing/absolute-position-headers-and-footers.html [ Failure ]
+crbug.com/303728 [ Win10 ] virtual/threaded/printing/fixed-positioned-but-static-headers-and-footers.html [ Failure ]
+crbug.com/303728 [ Win10 ] virtual/threaded/printing/fixed-positioned-headers-and-footers-clipped.html [ Failure ]
+crbug.com/303728 [ Win10 ] virtual/threaded/printing/fixed-positioned-headers-and-footers-inside-transform.html [ Failure ]
+crbug.com/303728 [ Win10 ] virtual/threaded/printing/fixed-positioned-headers-and-footers-larger-than-page.html [ Failure ]
+crbug.com/303728 [ Win10 ] virtual/threaded/printing/fixed-positioned-headers-and-footers.html [ Failure ]
+
 # Expected to fail until OffscreenCanvas can render on the gpu
 crbug.com/593514 virtual/gpu/fast/canvas/OffscreenCanvas-strokeRect-in-worker.html [ Failure ]
 crbug.com/593514 virtual/gpu/fast/canvas/OffscreenCanvas-paths-in-worker.html [ Failure ]
@@ -380,6 +395,11 @@
 
 crbug.com/475984 [ Mac Debug ] css2.1/t100801-c544-valgn-03-d-agi.html [ Failure ]
 
+crbug.com/591793 [ Mac ] fast/forms/textarea/basic-textareas-quirks.html [ NeedsRebaseline ]
+crbug.com/591793 [ Mac ] fast/forms/textarea/basic-textareas.html [ NeedsRebaseline ]
+crbug.com/591793 [ Mac ] fast/loader/text-document-wrapping.html [ NeedsRebaseline ]
+crbug.com/591793 [ Mac10.10 Mac10.11 Retina Win ] fast/text/midword-break-after-breakable-char.html [ NeedsRebaseline ]
+
 # Rebaseline didn't fix this. It's flaking between two different failures due to rounding error.
 # It consistently fails on debug builds and sometiems on release+asserts builds.
 # But consistently passes on release builds.
@@ -506,6 +526,7 @@
 # expectation files. The following tests with [ Failure ] don't have failure
 # expectation files because they contain local path names.
 # Use crbug.com/490511 for untriaged failures.
+crbug.com/490511 imported/web-platform-tests/dom/nodes/Document-contentType/contentType/contenttype_txt.html [ Timeout ]
 crbug.com/490511 [ Linux Win ] imported/web-platform-tests/html/rendering/bindings/the-input-element-as-a-text-entry-widget/unrecognized-type-should-fallback-as-text-type.html [ Failure ]
 crbug.com/526898 imported/web-platform-tests/html/rendering/non-replaced-elements/phrasing-content-0/font-element-text-decoration-color/001-x.xhtml [ Failure ]
 crbug.com/108417 imported/web-platform-tests/html/rendering/non-replaced-elements/tables/table-border-1.html [ Failure ]
@@ -1313,7 +1334,6 @@
 crbug.com/587593 [ Android ] fast/js/pic/cached-single-entry-transition.html [ Pass Failure ]
 
 crbug.com/587779 [ Linux Mac10.10 Mac10.11 Retina ] fast/dynamic/window-resize-scrollbars-test.html [ Timeout Failure Pass ]
-crbug.com/590043 media/media-document-audio-repaint.html [ NeedsRebaseline ]
 crbug.com/588103 fast/xmlhttprequest/xmlhttprequest-responsetype-arraybuffer.html [ Pass Failure ]
 
 crbug.com/594672 fast/events/iframe-object-onload.html [ Failure Pass ]
@@ -1361,8 +1381,205 @@
 crbug.com/453002 [ Win ] fast/text/justify-ideograph-vertical.html [ Failure Pass ]
 crbug.com/453002 [ Win ] fast/text/orientation-sideways.html [ Failure Pass ]
 
-crbug.com/599662 inspector/sources/debugger-ui/debugger-save-to-temp-var.html [ Failure Crash ]
-
 crbug.com/587737 [ Mac10.11 Retina ] virtual/gpu-rasterization/fast/images/color-profile-filter.html [ Timeout Failure ]
 
 crbug.com/599975 [ Android ] media/video-autoplay.html [ Timeout ]
+
+crbug.com/601166 [ Mac10.9 ]  fast/text-autosizing/tables/css-table-lots-of-text-many-cells.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text-autosizing/tables/css-table-single-cell-lots-of-text.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text-autosizing/tables/fixed-table-lots-of-text-many-cells.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text-autosizing/tables/fixed-table-single-cell-lots-of-text.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text-autosizing/tables/lots-of-text-many-cells.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text-autosizing/tables/narrow-percentage-width.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text-autosizing/tables/narrow-specified-width.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text-autosizing/tables/nested-table-wrapping.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text-autosizing/tables/nested-tables.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text-autosizing/tables/single-cell-lots-of-text.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text-autosizing/tables/single-percent-width-cell-lots-of-text.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text-autosizing/tables/table-cell-inflation.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text-autosizing/tables/table-for-layout.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text-autosizing/tables/wide-percentage-width.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text-autosizing/tables/wide-specified-width.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/aat-morx.html [ Failure Failure Failure Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/atsui-kerning-and-ligatures.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/atsui-multiple-renderers.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/atsui-partial-selection.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/atsui-pointtooffset-calls-cg.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/atsui-rtl-override-selection.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/atsui-small-caps-punctuation-size.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/atsui-spacing-features.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/basic/002.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/basic/003.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/basic/004.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/basic/005.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/basic/006.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/basic/007.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/basic/008.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/basic/011.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/basic/012.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/basic/013.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/basic/014.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/basic/015.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/basic/generic-family-changes.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/bidi-embedding-pop-and-push-same.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/bidi-img-alt-text.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/break-word.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/capitalize-boundaries.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/capitalize-empty-generated-string.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/capitalize-preserve-nbsp.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/caps-lock-indicator-disabled.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/caps-lock-indicator-enabled.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/cg-fallback-bolding.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/complex-path-with-no-subpixel-fonts.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/complex-preferred-logical-widths.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/complex-synthetic-bold-space-width.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/complex-text-rtl-selection-repaint.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/delete-hard-break-character.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/drawBidiText.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/embed-at-end-of-pre-wrap-line.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/emoji-web-font.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/emoticons.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/emphasis-complex.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/emphasis-ellipsis-complextext.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/emphasis.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/fake-italic.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/fallback-for-custom-font.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/firstline/001.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/firstline/002.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/firstline/003.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/font-ascent-mac.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/font-fallback.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/font-initial.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/font-smallcaps-layout.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/font-stretch-variant.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/font-stretch.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/font-weight-variant.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/font-weight.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/format-control.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/in-rendered-text-rtl.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/001.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/alef-connected.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/bidi-AN-after-L.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/bidi-AN-after-empty-run.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/bidi-CS-after-AN.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/bidi-L2-run-reordering.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/bidi-LDB-2-CSS.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/bidi-LDB-2-HTML.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/bidi-LDB-2-formatting-characters.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/bidi-control-chars-treated-as-ZWS.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/bidi-european-terminators.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/bidi-explicit-embedding.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/bidi-ignored-for-first-child-inline.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/bidi-innertext.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/bidi-layout-across-linebreak.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/bidi-linebreak-001.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/bidi-linebreak-002.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/bidi-linebreak-003.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/bidi-listbox-atsui.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/bidi-listbox.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/bidi-menulist.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/bidi-mirror-he-ar.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/bidi-neutral-directionality-paragraph-start.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/bidi-neutral-run.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/bidi-override.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/bold-bengali.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/complex-character-based-fallback.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/danda-space.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/hebrew-vowels.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/hindi-spacing.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/hindi-whitespace.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/khmer-selection.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/lang-glyph-cache-separation.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/menulist-width-rtl.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/mixed-directionality-selection.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/plane2.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/pop-up-button-text-alignment-and-direction.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/rtl-caret.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/rtl-negative-letter-spacing.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/rtl-white-space-pre-wrap.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/text-spliced-font.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/thai-baht-space.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/thai-line-breaks.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/unicode-bidi-plaintext-in-textarea.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/unicode-bidi-plaintext.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/international/wrap-CJK-001.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/justified-selection-at-edge.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/justified-selection.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/justify-ideograph-complex.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/justify-ideograph-simple.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/justify-ideograph-vertical.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/large-text-composed-char.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/line-breaks-after-white-space.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/line-breaks.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/line-initial-and-final-swashes.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/midword-break-after-breakable-char.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/midword-break-before-surrogate-pair.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/midword-break-hang.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/monospace-width-cache.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/reset-emptyRun.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/selection-hard-linebreak.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/selection-painting-hidpi.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/selection-rect-line-height-too-big.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/selection-rect-line-height-too-small.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/shadow-translucent-fill.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/shaping/same-script-different-lang.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/shaping/shaping-script-order.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/shaping/shaping-selection-rect.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/should-use-atsui.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/small-caps-turkish.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/softHyphen.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/text-letter-spacing.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/text-shadow-no-default-color.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/text-stroke-with-border.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/textIteratorNilRenderer.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/unicode-fallback-font.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/vertical-rl-rtl-linebreak.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/vertical-surrogate-pair.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/wbr-in-pre-crash.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/wbr-pre.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/wbr-styled.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/wbr.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/whitespace/001.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/whitespace/002.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/whitespace/003.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/whitespace/004.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/whitespace/005.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/whitespace/006.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/whitespace/007.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/whitespace/008.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/whitespace/009.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/whitespace/010.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/whitespace/011.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/whitespace/012.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/whitespace/015.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/whitespace/016.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/whitespace/018.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/whitespace/019.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/whitespace/020.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/whitespace/021.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/whitespace/023.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/whitespace/024.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/whitespace/025.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/whitespace/026.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/whitespace/027.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/whitespace/028.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/whitespace/029.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/whitespace/030.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/whitespace/normal-after-nowrap-breaking.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/whitespace/nowrap-clear-float.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/whitespace/pre-newline-box-test.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/whitespace/pre-wrap-last-char.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/whitespace/pre-wrap-line-test.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/whitespace/pre-wrap-overflow-selection.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/whitespace/pre-wrap-spaces-after-newline.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/whitespace/select-new-line-with-line-break-normal.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/whitespace/span-in-word-space-causes-overflow.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/wide-zero-width-space.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/word-break-run-rounding.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/word-break-soft-hyphen.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/word-break.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/word-space.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  fast/text/zero-font-size.html [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  ietestcenter/css3/text/textshadow-003.htm [ Failure ]
+crbug.com/601166 [ Mac10.9 ]  ietestcenter/css3/text/textshadow-004.htm [ Failure ]
+
diff --git a/third_party/WebKit/LayoutTests/bluetooth/requestDevice-sandboxed-iframe.html b/third_party/WebKit/LayoutTests/bluetooth/requestDevice-sandboxed-iframe.html
index e75b131..8d52e5e 100644
--- a/third_party/WebKit/LayoutTests/bluetooth/requestDevice-sandboxed-iframe.html
+++ b/third_party/WebKit/LayoutTests/bluetooth/requestDevice-sandboxed-iframe.html
@@ -14,8 +14,7 @@
         });
       } else {
         assert_equals(messageEvent.data, 'SecurityError: requestDevice() ' +
-                                         'called from sandboxed or otherwise ' +
-                                         'unique origin.');
+                                         'called from cross-origin iframe.');
         test.done();
       }
     });
@@ -23,7 +22,7 @@
       .then(() => {
         let iframe = document.createElement('iframe');
         iframe.sandbox.add('allow-scripts');
-        iframe.src = '../resources/bluetooth/requestDevice-in-sandboxed-iframe.html';
+        iframe.src = '../resources/bluetooth/requestDevice-in-iframe.html';
         document.body.appendChild(iframe);
       });
   }, 'Request device from a unique origin. Should reject with SecurityError.');
diff --git a/third_party/WebKit/LayoutTests/fast/css-grid-layout/min-height-border-box.html b/third_party/WebKit/LayoutTests/fast/css-grid-layout/min-height-border-box.html
index e565def..f6d8090 100644
--- a/third_party/WebKit/LayoutTests/fast/css-grid-layout/min-height-border-box.html
+++ b/third_party/WebKit/LayoutTests/fast/css-grid-layout/min-height-border-box.html
@@ -13,11 +13,12 @@
 }
 
 .container { width: 150px; }
-.borderPadding {
+.borderPaddingMargin {
     border-width: 2px 3px 5px 9px;
     border-color: blue;
     border-style: solid;
     padding: 4px 9px 12px 20px;
+    margin: 7px 10px 12px 14px;
 }
 
 </style>
@@ -37,8 +38,8 @@
 </div>
 
 <div class="container">
-    <div class="grid" data-expected-width="150" data-expected-height="58">
-        <div class="item borderPadding" data-expected-width="140" data-expected-height="48">XXX</div>
+    <div class="grid" data-expected-width="150" data-expected-height="77">
+        <div class="item borderPaddingMargin" data-expected-width="116" data-expected-height="48">XXX</div>
     </div>
 </div>
 
@@ -50,8 +51,8 @@
 </div>
 
 <div class="container">
-    <div class="grid" data-expected-width="150" data-expected-height="33">
-        <div class="item borderPadding" style="min-height: 0px;" data-expected-width="140" data-expected-height="23">XXX</div>
+    <div class="grid" data-expected-width="150" data-expected-height="52">
+        <div class="item borderPaddingMargin" style="min-height: 0px;" data-expected-width="116" data-expected-height="23">XXX</div>
     </div>
 </div>
 
@@ -63,8 +64,8 @@
 </div>
 
 <div class="container">
-    <div class="grid" data-expected-width="150" data-expected-height="33">
-        <div class="item alignSelfStart borderPadding" style="min-height: 0px;" data-expected-width="140" data-expected-height="48">XXX</div>
+    <div class="grid" data-expected-width="150" data-expected-height="52">
+        <div class="item alignSelfStart borderPaddingMargin" style="min-height: 0px;" data-expected-width="116" data-expected-height="48">XXX</div>
     </div>
 </div>
 
@@ -77,7 +78,7 @@
 
 <div class="container">
     <div class="grid" style="height: 15px;" data-expected-width="150" data-expected-height="25">
-        <div class="item borderPadding" style="min-height: 0px;" data-expected-width="140" data-expected-height="23">XXX</div>
+        <div class="item borderPaddingMargin" style="min-height: 0px;" data-expected-width="116" data-expected-height="23">XXX</div>
     </div>
 </div>
 
@@ -90,7 +91,7 @@
 
 <div class="container">
     <div class="grid" style="height: 15px;" data-expected-width="150" data-expected-height="25">
-        <div class="item alignSelfStart borderPadding" style="min-height: 0px;" data-expected-width="140" data-expected-height="48">XXX</div>
+        <div class="item alignSelfStart borderPaddingMargin" style="min-height: 0px;" data-expected-width="116" data-expected-height="48">XXX</div>
     </div>
 </div>
 
@@ -102,8 +103,8 @@
 </div>
 
 <div class="container">
-    <div class="grid" data-expected-width="150" data-expected-height="63">
-        <div class="item borderPadding" style="min-height: 30px;" data-expected-width="140" data-expected-height="53">XXX</div>
+    <div class="grid" data-expected-width="150" data-expected-height="82">
+        <div class="item borderPaddingMargin" style="min-height: 30px;" data-expected-width="116" data-expected-height="53">XXX</div>
     </div>
 </div>
 
@@ -115,8 +116,8 @@
 </div>
 
 <div class="container">
-    <div class="grid" data-expected-width="150" data-expected-height="63">
-        <div class="item alignSelfStart borderPadding" style="min-height: 30px;" data-expected-width="140" data-expected-height="53">XXX</div>
+    <div class="grid" data-expected-width="150" data-expected-height="82">
+        <div class="item alignSelfStart borderPaddingMargin" style="min-height: 30px;" data-expected-width="116" data-expected-height="53">XXX</div>
     </div>
 </div>
 
diff --git a/third_party/WebKit/LayoutTests/fast/css-grid-layout/min-width-margin-box.html b/third_party/WebKit/LayoutTests/fast/css-grid-layout/min-width-margin-box.html
new file mode 100644
index 0000000..1643dc6
--- /dev/null
+++ b/third_party/WebKit/LayoutTests/fast/css-grid-layout/min-width-margin-box.html
@@ -0,0 +1,147 @@
+<!DOCTYPE html>
+<link href="resources/grid.css" rel="stylesheet">
+<link href="resources/grid-alignment.css" rel="stylesheet">
+<link href="../css-intrinsic-dimensions/resources/width-keyword-classes.css" rel="stylesheet">
+<style>
+.grid {
+    border: 5px solid magenta;
+    margin-bottom: 60px;
+    grid-template-columns: minmax(auto, 0px);
+}
+
+.item {
+    font: 25px/1 Ahem;
+}
+
+.stretchedItem {
+    background-color: green;
+    grid-row: 2;
+    height: 15px;
+}
+
+.container { width: 150px; }
+
+.borderPaddingMargin {
+    margin: 7px 10px 12px 14px;
+    border-width: 2px 3px 5px 9px;
+    border-style: solid;
+    border-color: blue;
+    padding: 4px 9px 12px 20px;
+}
+
+</style>
+
+<script src="../../resources/testharness.js"></script>
+<script src="../../resources/testharnessreport.js"></script>
+<script src="../../resources/check-layout-th.js"></script>
+
+<body onload="checkLayout('.grid')">
+<div id="log"></div>
+
+<h3>grid width: auto</h3>
+<div class="container">
+    <div class="grid" data-expected-width="150" data-expected-height="50">
+        <div class="item" data-expected-width="100" data-expected-height="25">XXXX</div>
+        <div class="stretchedItem" data-expected-width="100" data-expected-height="15"></div>
+    </div>
+</div>
+
+<div class="container">
+    <div class="grid" data-expected-width="150" data-expected-height="92">
+        <div class="item borderPaddingMargin" data-expected-width="141" data-expected-height="48">XXXX</div>
+        <div class="stretchedItem" data-expected-width="165" data-expected-height="15"></div>
+    </div>
+</div>
+
+<h3>min-width: 0px. grid height: auto</h3>
+<div class="container">
+    <div class="grid" data-expected-width="150" data-expected-height="50">
+        <div class="item" style="min-width: 0px;" data-expected-width="0" data-expected-height="25">XXXX</div>
+        <div class="stretchedItem" data-expected-width="0" data-expected-height="15"></div>
+    </div>
+</div>
+
+<div class="container">
+    <div class="grid" data-expected-width="150" data-expected-height="92">
+        <div class="item borderPaddingMargin" style="min-width: 0px;" data-expected-width="41" data-expected-height="48">XXXX</div>
+        <div class="stretchedItem" data-expected-width="65" data-expected-height="15"></div>
+    </div>
+</div>
+
+<h3>min-width: 0px. grid height: 15px</h3>
+<div class="container">
+    <div class="grid" style="height: 15px;" data-expected-width="150" data-expected-height="25">
+        <div class="item" style="min-width: 0px;" data-expected-width="0" data-expected-height="25">XXXX</div>
+        <div class="stretchedItem" data-expected-width="0" data-expected-height="15"></div>
+    </div>
+</div>
+
+<div class="container">
+    <div class="grid" style="height: 15px;" data-expected-width="150" data-expected-height="25">
+        <div class="item border borderPaddingMargin" style="min-width: 0px;" data-expected-width="41" data-expected-height="48">XXXX</div>
+        <div class="stretchedItem" data-expected-width="65" data-expected-height="15"></div>
+    </div>
+</div>
+
+<h3>min-width: 125px. grid height: auto</h3>
+<div class="container">
+    <div class="grid" data-expected-width="150" data-expected-height="50">
+        <div class="item" style="min-width: 125px;" data-expected-width="125" data-expected-height="25">XXXX</div>
+        <div class="stretchedItem" data-expected-width="125" data-expected-height="15"></div>
+    </div>
+</div>
+
+<div class="container">
+    <div class="grid" data-expected-width="150" data-expected-height="92">
+        <div class="item borderPaddingMargin" style="min-width: 125px;" data-expected-width="166" data-expected-height="48">XXXX</div>
+        <div class="stretchedItem" data-expected-width="190" data-expected-height="15"></div>
+    </div>
+</div>
+
+<h3>min-width: 50%. grid height: auto</h3>
+<div class="container">
+    <div class="grid" data-expected-width="150" data-expected-height="75">
+        <div class="item" style="min-width: 50%;" data-expected-width="0" data-expected-height="50">XXX XX</div>
+        <div class="stretchedItem" data-expected-width="0" data-expected-height="15"></div>
+    </div>
+</div>
+
+<div class="container">
+    <div class="grid" data-expected-width="150" data-expected-height="117">
+        <div class="item borderPaddingMargin" style="min-width: 50%;" data-expected-width="74" data-expected-height="73">XXX XX</div>
+        <div class="stretchedItem" data-expected-width="65" data-expected-height="15"></div>
+    </div>
+</div>
+
+
+<h3>min-width: min-content. grid height: auto</h3>
+<div class="container">
+    <div class="grid" data-expected-width="150" data-expected-height="75">
+        <div class="item min-width-min-content" data-expected-width="75" data-expected-height="50">XXX XX</div>
+        <div class="stretchedItem" data-expected-width="75" data-expected-height="15"></div>
+    </div>
+</div>
+
+<div class="container">
+    <div class="grid" data-expected-width="150" data-expected-height="117">
+        <div class="item borderPaddingMargin min-width-min-content" data-expected-width="116" data-expected-height="73">XXX XX</div>
+        <div class="stretchedItem" data-expected-width="140" data-expected-height="15"></div>
+    </div>
+</div>
+
+<h3>min-width: max-content. grid height: auto</h3>
+<div class="container">
+    <div class="grid" data-expected-width="150" data-expected-height="50">
+        <div class="item alignSelfStart min-width-max-content" data-expected-width="150" data-expected-height="25">XXX XX</div>
+        <div class="stretchedItem" data-expected-width="150" data-expected-height="15"></div>
+    </div>
+</div>
+
+<div class="container">
+    <div class="grid" data-expected-width="150" data-expected-height="92">
+        <div class="item alignSelfStart borderPaddingMargin min-width-max-content" data-expected-width="191" data-expected-height="48">XXX XX</div>
+        <div class="stretchedItem" data-expected-width="215" data-expected-height="15"></div>
+    </div>
+</div>
+
+</body>
diff --git a/third_party/WebKit/LayoutTests/fast/css/window-internals-isCSSPropertyUseCounted.html b/third_party/WebKit/LayoutTests/fast/css/window-internals-isCSSPropertyUseCounted.html
index 5abe850..65356b6 100644
--- a/third_party/WebKit/LayoutTests/fast/css/window-internals-isCSSPropertyUseCounted.html
+++ b/third_party/WebKit/LayoutTests/fast/css/window-internals-isCSSPropertyUseCounted.html
@@ -3,7 +3,7 @@
 <script src="../../resources/testharnessreport.js"></script>
 
 <style>
-div {
+#target1 {
 	padding-left: 100px;
 	padding-bottom: 100px;
 	color:green;
@@ -13,9 +13,14 @@
 	border-left: thick dashed lightgreen;
 	-webkit-border-end-color: pink;
 }
+#target2 {
+  -webkit-align-content: space-between;
+  transform: translate(100px);
+}
 </style>
 
-<div id="target"></div>
+<div id="target1"></div>
+<div id="target2"></div>
 
 <script>
 test(function() {
@@ -47,4 +52,12 @@
 	assert_false(internals.isCSSPropertyUseCounted(document, "box-sizing"));
 }, "Test that properties specified in UA stylesheet aren't counted");
 
+test(function() {
+  assert_false(internals.isCSSPropertyUseCounted(document, "align-content"));
+  assert_true(internals.isCSSPropertyUseCounted(document, "-webkit-align-content"));
+  assert_false(internals.isCSSPropertyUseCounted(document, "-webkit-transform"));
+  assert_true(internals.isCSSPropertyUseCounted(document, "transform"));
+}, "Test properties with aliases");
+
+
 </script>
\ No newline at end of file
diff --git a/third_party/WebKit/LayoutTests/fast/dom/shadow/resources/shadow-dom.js b/third_party/WebKit/LayoutTests/fast/dom/shadow/resources/shadow-dom.js
index 1b19dd35..c734253e 100644
--- a/third_party/WebKit/LayoutTests/fast/dom/shadow/resources/shadow-dom.js
+++ b/third_party/WebKit/LayoutTests/fast/dom/shadow/resources/shadow-dom.js
@@ -190,7 +190,7 @@
 {
     var element = getNodeInComposedTree(id);
     if (!element) {
-        debug('FAIL: There is no such element with id: '+ from);
+        debug('FAIL: There is no such element with id: '+ id);
         return false;
     }
     if (element == innermostActiveElement())
diff --git a/third_party/WebKit/LayoutTests/fast/speechsynthesis/speech-synthesis-mock-no-crash-expected.txt b/third_party/WebKit/LayoutTests/fast/speechsynthesis/speech-synthesis-mock-no-crash-expected.txt
new file mode 100644
index 0000000..c8386a8
--- /dev/null
+++ b/third_party/WebKit/LayoutTests/fast/speechsynthesis/speech-synthesis-mock-no-crash-expected.txt
@@ -0,0 +1,11 @@
+This tests that the mock speech synthesizer is well behaved when attempting to pause/resume without first speaking.
+
+On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
+
+
+PASS speechSynthesis.pause() is undefined.
+PASS speechSynthesis.resume() is undefined.
+PASS successfullyParsed is true
+
+TEST COMPLETE
+
diff --git a/third_party/WebKit/LayoutTests/fast/speechsynthesis/speech-synthesis-mock-no-crash.html b/third_party/WebKit/LayoutTests/fast/speechsynthesis/speech-synthesis-mock-no-crash.html
new file mode 100644
index 0000000..4d80fc8
--- /dev/null
+++ b/third_party/WebKit/LayoutTests/fast/speechsynthesis/speech-synthesis-mock-no-crash.html
@@ -0,0 +1,16 @@
+<!DOCTYPE html>
+<html>
+<head>
+<script src="../../resources/js-test.js"></script>
+</head>
+<script>
+    description("This tests that the mock speech synthesizer is well behaved when attempting to pause/resume without first speaking.");
+
+    if (window.internals)
+        window.internals.enableMockSpeechSynthesizer(document);
+
+    shouldBeUndefined("speechSynthesis.pause()");
+    shouldBeUndefined("speechSynthesis.resume()");
+</script>
+</body>
+</html>
diff --git a/third_party/WebKit/LayoutTests/fast/text/break-word-fit-content-arabic-expected.html b/third_party/WebKit/LayoutTests/fast/text/break-word-fit-content-arabic-expected.html
new file mode 100644
index 0000000..3a9bb69
--- /dev/null
+++ b/third_party/WebKit/LayoutTests/fast/text/break-word-fit-content-arabic-expected.html
@@ -0,0 +1,8 @@
+<!DOCTYPE html>
+<meta charset="utf-8">
+<style>
+div {
+  font-size: 600%;
+}
+</style>
+<div>ثثبو</div>
diff --git a/third_party/WebKit/LayoutTests/fast/text/break-word-fit-content-arabic.html b/third_party/WebKit/LayoutTests/fast/text/break-word-fit-content-arabic.html
new file mode 100644
index 0000000..e27a775
--- /dev/null
+++ b/third_party/WebKit/LayoutTests/fast/text/break-word-fit-content-arabic.html
@@ -0,0 +1,10 @@
+<!DOCTYPE html>
+<meta charset="utf-8">
+<style>
+div {
+  font-size: 600%;
+  display: inline-block;
+  word-wrap: break-word;
+}
+</style>
+<div>ثثبو</div>
diff --git a/third_party/WebKit/LayoutTests/fast/text/break-word-pre-wrap-expected.html b/third_party/WebKit/LayoutTests/fast/text/break-word-pre-wrap-expected.html
new file mode 100644
index 0000000..341000e
--- /dev/null
+++ b/third_party/WebKit/LayoutTests/fast/text/break-word-pre-wrap-expected.html
@@ -0,0 +1,22 @@
+<!DOCTYPE html>
+<style>
+div {
+  font-family: 'Courier New';
+  font-family: 'Ahem';
+  border: thin solid black;
+  white-space: pre;
+  display: inline-block;
+  vertical-align: top;
+}
+.c5 { width: 5.1ch; }
+.c6 { width: 6.1ch; }
+</style>
+<div class="c5">Lorem<br>Ipsum<br>dollo<br>ABCDE<br>FGHI</div>
+<div class="c5">Lorem<br>Ipsum<br><br>dollo<br>ABCDE<br>FGHI</div>
+<div class="c5">Lorem<br><br>Ipsum<br><br>dollo<br>ABCDE<br>FGHI</div>
+<div class="c5">Lorem<br><br>Ipsum<br><br>dollo<br>ABCDE<br>FGHI</div>
+<br>
+<div class="c6">Lorem<br>Ipsum<br>dollo<br>ABCDEF<br>GHI</div>
+<div class="c6">Lorem<br>Ipsum<br>dollo<br>ABCDEF<br>GHI</div>
+<div class="c6">Lorem<br>Ipsum<br>dollo<br>ABCDEF<br>GHI</div>
+<div class="c6">Lorem<br>Ipsum<br>dollo<br>ABCDEF<br>GHI</div>
diff --git a/third_party/WebKit/LayoutTests/fast/text/break-word-pre-wrap.html b/third_party/WebKit/LayoutTests/fast/text/break-word-pre-wrap.html
new file mode 100644
index 0000000..5d3b714
--- /dev/null
+++ b/third_party/WebKit/LayoutTests/fast/text/break-word-pre-wrap.html
@@ -0,0 +1,23 @@
+<!DOCTYPE html>
+<style>
+div {
+  font-family: 'Courier New';
+  font-family: 'Ahem';
+  border: thin solid black;
+  white-space: pre-wrap;
+  word-wrap: break-word;
+  display: inline-block;
+  vertical-align: top;
+}
+.c5 { width: 5.1ch; }
+.c6 { width: 6.1ch; }
+</style>
+<div class="c5">Lorem Ipsum dollo ABCDEFGHI</div>
+<div class="c5">Lorem Ipsum  dollo ABCDEFGHI</div>
+<div class="c5">Lorem  Ipsum  dollo ABCDEFGHI</div>
+<div class="c5">Lorem   Ipsum   dollo ABCDEFGHI</div>
+<br>
+<div class="c6">Lorem Ipsum dollo ABCDEFGHI</div>
+<div class="c6">Lorem Ipsum  dollo ABCDEFGHI</div>
+<div class="c6">Lorem  Ipsum  dollo ABCDEFGHI</div>
+<div class="c6">Lorem   Ipsum   dollo ABCDEFGHI</div>
diff --git a/third_party/WebKit/LayoutTests/http/tests/bluetooth/https/requestDevice/cross-origin-iframe.html b/third_party/WebKit/LayoutTests/http/tests/bluetooth/https/requestDevice/cross-origin-iframe.html
new file mode 100644
index 0000000..11917a2
--- /dev/null
+++ b/third_party/WebKit/LayoutTests/http/tests/bluetooth/https/requestDevice/cross-origin-iframe.html
@@ -0,0 +1,29 @@
+<!DOCTYPE html>
+<script src="/js-test-resources/testharness.js"></script>
+<script src="/js-test-resources/testharnessreport.js"></script>
+<script src="/js-test-resources/bluetooth/bluetooth-helpers.js"></script>
+<body>
+  <script>
+  "use strict";
+  async_test(test => {
+    window.onmessage = messageEvent => test.step(() => {
+      if (messageEvent.data === 'Ready') {
+        let iframe = document.querySelector('iframe');
+        callWithKeyDown(() => {
+          iframe.contentWindow.postMessage('Go', '*');
+        });
+      } else {
+        assert_equals(messageEvent.data, 'SecurityError: requestDevice() ' +
+                                         'called from cross-origin iframe.');
+        test.done();
+      }
+    });
+    setBluetoothFakeAdapter('HeartRateAdapter')
+      .then(() => {
+        let iframe = document.createElement('iframe');
+        iframe.src = 'https://localhost:8443/js-test-resources/bluetooth/requestDevice-in-iframe.html';
+        document.body.appendChild(iframe);
+      });
+  }, 'Request device from a unique origin. Should reject with SecurityError.');
+  </script>
+</body>
diff --git a/third_party/WebKit/LayoutTests/http/tests/serviceworker/controller-on-load.html b/third_party/WebKit/LayoutTests/http/tests/serviceworker/controller-on-load.html
index 5a6a447..99bdc20 100644
--- a/third_party/WebKit/LayoutTests/http/tests/serviceworker/controller-on-load.html
+++ b/third_party/WebKit/LayoutTests/http/tests/serviceworker/controller-on-load.html
@@ -14,7 +14,7 @@
           return wait_for_state(t, registration.installing, 'activated');
         }))
       .then(t.step_func(function() {
-          return with_iframe(scope)
+          return with_iframe(scope);
         }))
       .then(t.step_func(function(frame) {
           var w = frame.contentWindow;
diff --git a/third_party/WebKit/LayoutTests/http/tests/serviceworker/fetch-mixed-content-to-outscope-expected.txt b/third_party/WebKit/LayoutTests/http/tests/serviceworker/fetch-mixed-content-to-outscope-expected.txt
index b4289bcd..bf6a0d8 100644
--- a/third_party/WebKit/LayoutTests/http/tests/serviceworker/fetch-mixed-content-to-outscope-expected.txt
+++ b/third_party/WebKit/LayoutTests/http/tests/serviceworker/fetch-mixed-content-to-outscope-expected.txt
@@ -1,7 +1,6 @@
 CONSOLE ERROR: Mixed Content: The page at 'https://127.0.0.1:8443/serviceworker/resources/fetch-mixed-content-iframe-inscope-to-outscope.html' was loaded over HTTPS, but requested an insecure image 'http://127.0.0.1:8000/serviceworker/resources/fetch-access-control.php?PNGIMAGE'. This request has been blocked; the content must be served over HTTPS.
 CONSOLE ERROR: Mixed Content: The page at 'https://127.0.0.1:8443/serviceworker/resources/fetch-mixed-content-iframe-inscope-to-outscope.html' was loaded over HTTPS, but requested an insecure image 'http://localhost:8000/serviceworker/resources/fetch-access-control.php?PNGIMAGE'. This request has been blocked; the content must be served over HTTPS.
-
-This is a testharness.js-based test.
+ This is a testharness.js-based test.
 PASS Verify Mixed content of fetch() in a Service Worker 
 Harness: the test ran to completion.
 
diff --git a/third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/navigation-redirect-to-http-iframe.html b/third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/navigation-redirect-to-http-iframe.html
index 52b5042..234ba15 100644
--- a/third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/navigation-redirect-to-http-iframe.html
+++ b/third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/navigation-redirect-to-http-iframe.html
@@ -32,7 +32,7 @@
 function on_state_change(event) {
   if (event.target.state != 'activated')
     return;
-  with_iframe(SCOPE)
+  with_iframe(SCOPE, {auto_remove: false})
     .then(function(frame) {
         window.parent.postMessage(
             {results: frame.contentDocument.body.textContent},
diff --git a/third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/test-helpers.js b/third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/test-helpers.js
index 6521566..1859b2a 100644
--- a/third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/test-helpers.js
+++ b/third_party/WebKit/LayoutTests/http/tests/serviceworker/resources/test-helpers.js
@@ -44,14 +44,21 @@
 }
 
 // Adds an iframe to the document and returns a promise that resolves to the
-// iframe when it finishes loading. The caller is responsible for removing the
-// iframe later if needed.
-function with_iframe(url) {
+// iframe when it finishes loading. When |options.auto_remove| is set to
+// |false|, the caller is responsible for removing the iframe
+// later. Otherwise, the frame will be removed after all tests are finished.
+function with_iframe(url, options) {
   return new Promise(function(resolve) {
       var frame = document.createElement('iframe');
       frame.src = url;
       frame.onload = function() { resolve(frame); };
       document.body.appendChild(frame);
+      if (typeof options === 'undefined')
+        options = {};
+      if (typeof options.auto_remove === 'undefined')
+        options.auto_remove = true;
+      if (options.auto_remove)
+        add_completion_callback(function() { frame.remove(); });
     });
 }
 
diff --git a/third_party/WebKit/LayoutTests/http/tests/serviceworker/sync-xhr-doesnt-deadlock-expected.txt b/third_party/WebKit/LayoutTests/http/tests/serviceworker/sync-xhr-doesnt-deadlock-expected.txt
index c302a08..463c83c 100644
--- a/third_party/WebKit/LayoutTests/http/tests/serviceworker/sync-xhr-doesnt-deadlock-expected.txt
+++ b/third_party/WebKit/LayoutTests/http/tests/serviceworker/sync-xhr-doesnt-deadlock-expected.txt
@@ -1,5 +1,4 @@
 CONSOLE WARNING: Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
-
 This is a testharness.js-based test.
 PASS Verify SyncXHR does not deadlock 
 Harness: the test ran to completion.
diff --git a/third_party/WebKit/LayoutTests/platform/android/media/media-document-audio-repaint-expected.txt b/third_party/WebKit/LayoutTests/platform/android/media/media-document-audio-repaint-expected.txt
new file mode 100644
index 0000000..1043ff3
--- /dev/null
+++ b/third_party/WebKit/LayoutTests/platform/android/media/media-document-audio-repaint-expected.txt
@@ -0,0 +1,42 @@
+layer at (0,0) size 800x600
+  LayoutView at (0,0) size 800x600
+layer at (0,0) size 800x600
+  LayoutBlockFlow {HTML} at (0,0) size 800x600
+    LayoutBlockFlow {BODY} at (8,8) size 784x584
+      LayoutBlockFlow {P} at (0,0) size 784x20
+        LayoutText {#text} at (0,0) size 701x19
+          text run at (0,0) width 620: "This tests that in a standalone media document with audio content, the media element repaints correctly "
+          text run at (620,0) width 81: "while playing."
+      LayoutBlockFlow (anonymous) at (0,36) size 784x334
+        LayoutText {#text} at (0,0) size 0x0
+        LayoutText {#text} at (0,0) size 0x0
+layer at (8,44) size 384x334
+  LayoutIFrame {IFRAME} at (0,0) size 384x334 [border: (2px inset #EEEEEE)]
+    layer at (0,0) size 380x330
+      LayoutView at (0,0) size 380x330
+    layer at (0,0) size 380x330
+      LayoutBlockFlow {HTML} at (0,0) size 380x330
+        LayoutBlockFlow {BODY} at (8,8) size 364x314 [bgcolor=#000000]
+    layer at (40,165) size 300x1
+      LayoutVideo (positioned) {VIDEO} at (40,164.50) size 300x1
+    layer at (40,165) size 300x1
+      LayoutFlexibleBox (relative positioned) {DIV} at (0,0) size 300x1
+        LayoutBlockFlow {DIV} at (0,-34) size 300x35
+    layer at (40,131) size 300x0
+      LayoutFlexibleBox (relative positioned) {DIV} at (0,-34) size 300x0
+    layer at (45,131) size 290x30
+      LayoutFlexibleBox (relative positioned) {DIV} at (5,0) size 290x30 [bgcolor=#141414CC]
+        LayoutButton {INPUT} at (9,0) size 30x30
+        LayoutSlider {INPUT} at (48,11) size 98.47x8
+          LayoutFlexibleBox {DIV} at (0,0) size 98.47x8 [border: (1px solid #E6E6E659)]
+            LayoutBlockFlow {DIV} at (1,-8) size 110.47x24
+              LayoutBlockFlow {DIV} at (32.22,0) size 32x24
+        LayoutFlexibleBox {DIV} at (161.47,0) size 25x30 [color=#FFFFFF]
+          LayoutBlockFlow (anonymous) at (0,0) size 25x30
+            LayoutText {#text} at (0,7) size 25x16
+              text run at (0,7) width 25: "0:00"
+        LayoutButton {INPUT} at (195.47,0) size 35x30
+        LayoutSlider {INPUT} at (236.47,11) size 38.53x8
+          LayoutFlexibleBox {DIV} at (0,0) size 38.53x8 [border: (1px solid #E6E6E659)]
+            LayoutBlockFlow {DIV} at (1,-8) size 50.53x24
+              LayoutBlockFlow {DIV} at (19.53,0) size 24x24
diff --git a/third_party/WebKit/LayoutTests/platform/linux/media/media-document-audio-repaint-expected.txt b/third_party/WebKit/LayoutTests/platform/linux/media/media-document-audio-repaint-expected.txt
index 1043ff3..16aa57f 100644
--- a/third_party/WebKit/LayoutTests/platform/linux/media/media-document-audio-repaint-expected.txt
+++ b/third_party/WebKit/LayoutTests/platform/linux/media/media-document-audio-repaint-expected.txt
@@ -16,9 +16,10 @@
       LayoutView at (0,0) size 380x330
     layer at (0,0) size 380x330
       LayoutBlockFlow {HTML} at (0,0) size 380x330
-        LayoutBlockFlow {BODY} at (8,8) size 364x314 [bgcolor=#000000]
+        LayoutBlockFlow {BODY} at (0,0) size 380x330 [bgcolor=#000000]
+          LayoutFlexibleBox {DIV} at (0,0) size 380x330
     layer at (40,165) size 300x1
-      LayoutVideo (positioned) {VIDEO} at (40,164.50) size 300x1
+      LayoutVideo {VIDEO} at (40,164.50) size 300x1
     layer at (40,165) size 300x1
       LayoutFlexibleBox (relative positioned) {DIV} at (0,0) size 300x1
         LayoutBlockFlow {DIV} at (0,-34) size 300x35
diff --git a/third_party/WebKit/LayoutTests/platform/mac/media/media-document-audio-repaint-expected.txt b/third_party/WebKit/LayoutTests/platform/mac/media/media-document-audio-repaint-expected.txt
index 964449df..15329f6 100644
--- a/third_party/WebKit/LayoutTests/platform/mac/media/media-document-audio-repaint-expected.txt
+++ b/third_party/WebKit/LayoutTests/platform/mac/media/media-document-audio-repaint-expected.txt
@@ -16,9 +16,10 @@
       LayoutView at (0,0) size 380x330
     layer at (0,0) size 380x330
       LayoutBlockFlow {HTML} at (0,0) size 380x330
-        LayoutBlockFlow {BODY} at (8,8) size 364x314 [bgcolor=#000000]
+        LayoutBlockFlow {BODY} at (0,0) size 380x330 [bgcolor=#000000]
+          LayoutFlexibleBox {DIV} at (0,0) size 380x330
     layer at (40,165) size 300x1
-      LayoutVideo (positioned) {VIDEO} at (40,164.50) size 300x1
+      LayoutVideo {VIDEO} at (40,164.50) size 300x1
     layer at (40,165) size 300x1
       LayoutFlexibleBox (relative positioned) {DIV} at (0,0) size 300x1
         LayoutBlockFlow {DIV} at (0,-34) size 300x35
diff --git a/third_party/WebKit/LayoutTests/platform/win/media/media-document-audio-repaint-expected.txt b/third_party/WebKit/LayoutTests/platform/win/media/media-document-audio-repaint-expected.txt
index 093febf..3653704 100644
--- a/third_party/WebKit/LayoutTests/platform/win/media/media-document-audio-repaint-expected.txt
+++ b/third_party/WebKit/LayoutTests/platform/win/media/media-document-audio-repaint-expected.txt
@@ -16,9 +16,10 @@
       LayoutView at (0,0) size 380x330
     layer at (0,0) size 380x330
       LayoutBlockFlow {HTML} at (0,0) size 380x330
-        LayoutBlockFlow {BODY} at (8,8) size 364x314 [bgcolor=#000000]
+        LayoutBlockFlow {BODY} at (0,0) size 380x330 [bgcolor=#000000]
+          LayoutFlexibleBox {DIV} at (0,0) size 380x330
     layer at (40,165) size 300x1
-      LayoutVideo (positioned) {VIDEO} at (40,164.50) size 300x1
+      LayoutVideo {VIDEO} at (40,164.50) size 300x1
     layer at (40,165) size 300x1
       LayoutFlexibleBox (relative positioned) {DIV} at (0,0) size 300x1
         LayoutBlockFlow {DIV} at (0,-34) size 300x35
diff --git a/third_party/WebKit/LayoutTests/resources/bluetooth/requestDevice-in-iframe.html b/third_party/WebKit/LayoutTests/resources/bluetooth/requestDevice-in-iframe.html
index ac51b0744..870e7a8 100644
--- a/third_party/WebKit/LayoutTests/resources/bluetooth/requestDevice-in-iframe.html
+++ b/third_party/WebKit/LayoutTests/resources/bluetooth/requestDevice-in-iframe.html
@@ -1,6 +1,8 @@
 <!DOCTYPE html>
 <script>
   window.onmessage = messageEvent => {
+    // For requestDevice to work, 'Go' should be sent while
+    // handling a user gesture.
     if (messageEvent.data === 'Go') {
       navigator.bluetooth.requestDevice({
         filters: [{services: ['generic_access']}]
@@ -11,8 +13,7 @@
           parent.postMessage('FAIL: requestDevice in iframe returned ' + device, '*');
         }
       }).catch(err => {
-        console.error(err);
-        parent.postMessage('FAIL: ' + err, '*');
+        parent.postMessage(err.name + ': ' + err.message, '*');
       });
     }
   };
diff --git a/third_party/WebKit/LayoutTests/resources/bluetooth/requestDevice-in-sandboxed-iframe.html b/third_party/WebKit/LayoutTests/resources/bluetooth/requestDevice-in-sandboxed-iframe.html
deleted file mode 100644
index 10fa000..0000000
--- a/third_party/WebKit/LayoutTests/resources/bluetooth/requestDevice-in-sandboxed-iframe.html
+++ /dev/null
@@ -1,18 +0,0 @@
-<!DOCTYPE html>
-<button onclick="RequestDevice()">Request</button>
-<script>
-  window.onmessage = messageEvent => {
-    // For requestDevice to work, 'Go' should be sent while
-    // handling a user gesture.
-    if (messageEvent.data === 'Go') {
-      navigator.bluetooth.requestDevice({
-        filters: [{services: ['heart_rate']}]
-      }).then(() => {
-        parent.postMessage('Should have failed.', '*');
-      }).catch(err => {
-        parent.postMessage(err.name + ': ' + err.message, '*');
-      });
-    }
-  };
-  parent.postMessage("Ready", "*");
-</script>
diff --git a/third_party/WebKit/LayoutTests/shadow-dom/focus-navigation-with-delegatesFocus-expected.txt b/third_party/WebKit/LayoutTests/shadow-dom/focus-navigation-with-delegatesFocus-expected.txt
index 0740e32..8f0cb3a 100644
--- a/third_party/WebKit/LayoutTests/shadow-dom/focus-navigation-with-delegatesFocus-expected.txt
+++ b/third_party/WebKit/LayoutTests/shadow-dom/focus-navigation-with-delegatesFocus-expected.txt
@@ -52,13 +52,9 @@
 (5/8) Testing tab navigation order with tabindex=-1 and delegatesFocus=false
 PASS window.internals.shadowRoot(hostDiv).delegatesFocus is false
 PASS hostDiv.getAttribute("tabindex") is "-1"
-Should move from input-before to host-div/inner-input in forward
+Should move from input-before to input-after in forward
 PASS
-Should move from host-div/inner-input to input-after in forward
-PASS
-Should move from input-after to host-div/inner-input in backward
-PASS
-Should move from host-div/inner-input to input-before in backward
+Should move from input-after to input-before in backward
 PASS
 (6/8) Testing tab navigation order with tabindex=-1 and delegatesFocus=true
 PASS window.internals.shadowRoot(hostDiv).delegatesFocus is true
@@ -144,13 +140,9 @@
 (5/8) Testing tab navigation order with tabindex=-1 and delegatesFocus=false
 PASS window.internals.shadowRoot(hostDiv).delegatesFocus is false
 PASS hostDiv.getAttribute("tabindex") is "-1"
-Should move from input-before to host-div/inner-input in forward
+Should move from input-before to input-after in forward
 PASS
-Should move from host-div/inner-input to input-after in forward
-PASS
-Should move from input-after to host-div/inner-input in backward
-PASS
-Should move from host-div/inner-input to input-before in backward
+Should move from input-after to input-before in backward
 PASS
 (6/8) Testing tab navigation order with tabindex=-1 and delegatesFocus=true
 PASS window.internals.shadowRoot(hostDiv).delegatesFocus is true
diff --git a/third_party/WebKit/LayoutTests/shadow-dom/focus-navigation-with-delegatesFocus.html b/third_party/WebKit/LayoutTests/shadow-dom/focus-navigation-with-delegatesFocus.html
index 13c8d3a..2d18973 100644
--- a/third_party/WebKit/LayoutTests/shadow-dom/focus-navigation-with-delegatesFocus.html
+++ b/third_party/WebKit/LayoutTests/shadow-dom/focus-navigation-with-delegatesFocus.html
@@ -113,7 +113,6 @@
 
     expectedOrder = [
       'input-before',
-      'host-div/inner-input',
       'input-after'
     ];
 
diff --git a/third_party/WebKit/LayoutTests/shadow-dom/focus-with-negative-index.html b/third_party/WebKit/LayoutTests/shadow-dom/focus-with-negative-index.html
new file mode 100644
index 0000000..802f39a
--- /dev/null
+++ b/third_party/WebKit/LayoutTests/shadow-dom/focus-with-negative-index.html
@@ -0,0 +1,92 @@
+<!DOCTYPE html>
+<script src='../resources/testharness.js'></script>
+<script src='../resources/testharnessreport.js'></script>
+<script src='../fast/dom/shadow/resources/shadow-dom.js'></script>
+<script src='resources/shadow-dom.js'></script>
+<div id="log"></div>
+<p>
+  document tree: [i0 -> [x-foo]]<br>
+  x-foo's shadow tree: [j5 -> [x-bar] -> j6]<br>
+  x-bar's shadow tree: [k1 -> k0 -> [s2]]<br>
+  slot #s2: [j1 -> j2 -> j3 -> j4 -> [s1] -> j0]<br><br>
+  slot #s1: [i1 -> i2]<br>
+  <b>v1 ideal nav forward:  [i0 -> j5 -> xbar -> k1 -> k0 -> j6]</b><br>
+</p>
+
+  <input id="i0" tabindex=0 value="i0">
+  <div id="x-foo">
+    <input id="i2" slot="s1" tabindex=2 value="i2">
+    <input id="i1" slot="s1" tabindex=1 value="i1">
+    <template data-mode="open">
+      <div id="x-bar" tabindex=4>
+        <input id="j1" slot="s2" tabindex=1 value="j1">
+        <slot id="s1" name="s1" slot="s2"></slot>
+        <input id="j0" slot="s2" tabindex=0 value="j0">
+        <input id="j3" slot="s2" tabindex=2 value="j3">
+        <div id="j4" slot="s2" tabindex=3>
+          <input id="j2" tabindex=1 value="j2">
+        </div>
+        <template data-mode="open">
+          <input id="k0" tabindex=0 value="k0">
+          <slot id="s2" name="s2" tabindex=-1></slot>
+          <input id="k1" tabindex=1 value="k1">
+        </template>
+      </div>
+      <div id="to-be-ignored-host" tabindex=-1>
+        <template data-mode="open">
+          <input id="ignored-input-in-shadow-host1" tabindex=1 value="ignored">
+          <input id="ignored-input-in-shadow-host2" tabindex=2 value="ignored">
+        </template>
+      </div>
+      <input id="j6" tabindex=4 value="j6">
+      <input id="j5" tabindex=3 value="j5">
+    </template>
+  </div>
+</div>
+
+<script>
+
+var xfoo = document.getElementById('x-foo');
+convertTemplatesToShadowRootsWithin(xfoo);
+var sr = xfoo.shadowRoot;
+test(function() {
+  var elements = [
+    'i0',
+    'x-foo/j5',
+    'x-foo/x-bar',
+    'x-foo/x-bar/k1',
+    'x-foo/x-bar/k0',
+    'x-foo/j6'
+  ];
+
+  for (var i = 0; i + 1 < elements.length; ++i)
+      assert_true(shouldNavigateFocus(elements[i], elements[i + 1], 'forward'), elements[i] + " to " + elements[i + 1]);
+  elements.reverse();
+  for (var i = 0; i + 1 < elements.length; ++i)
+      assert_true(shouldNavigateFocus(elements[i], elements[i + 1], 'backward'), elements[i] + " to " + elements[i + 1]);
+}, 'Focus controller should treat slots as a focus scope.');
+
+test(function() {
+  var ignoredHost = sr.getElementById('to-be-ignored-host');
+  var ignoredInput1 = ignoredHost.shadowRoot.querySelector('input');
+  var ignoredInput2 = ignoredInput1.nextElementSibling;
+
+  var elements = [
+    'x-foo/to-be-ignored-host/ignored-input-in-shadow-host1',
+    'x-foo/to-be-ignored-host/ignored-input-in-shadow-host2',
+    'x-foo/j6'
+  ];
+  for (var i = 0; i + 1 < elements.length; ++i)
+      assert_true(shouldNavigateFocus(elements[i], elements[i + 1], 'forward'), elements[i] + " to " + elements[i + 1]);
+
+  var elementsBackward = [
+    'x-foo/to-be-ignored-host/ignored-input-in-shadow-host2',
+    'x-foo/to-be-ignored-host/ignored-input-in-shadow-host1',
+    'x-foo/x-bar/k0'
+  ];
+  for (var i = 0; i + 1 < elements.length; ++i)
+      assert_true(shouldNavigateFocus(elementsBackward[i], elementsBackward[i + 1], 'backward'), elementsBackward[i] + " to " + elementsBackward[i + 1]);
+
+}, 'This is a regression test: After focusing negative tabindex-ed elements, focus moves in tree order.');
+
+</script>
diff --git a/third_party/WebKit/PRESUBMIT.py b/third_party/WebKit/PRESUBMIT.py
index e01a5e4..cdbb66a 100644
--- a/third_party/WebKit/PRESUBMIT.py
+++ b/third_party/WebKit/PRESUBMIT.py
@@ -217,7 +217,7 @@
     """Checks that Blink uses Chromium namespaces only in permitted code."""
     # This list is not exhaustive, but covers likely ones.
     chromium_namespaces = ["base", "cc", "content", "gfx", "net", "ui"]
-    chromium_classes = ["scoped_ptr", "scoped_refptr"]
+    chromium_classes = ["scoped_refptr"]
 
     def source_file_filter(path):
         return input_api.FilterSourceFile(path,
diff --git a/third_party/WebKit/PerformanceTests/Bindings/resources/worker.js b/third_party/WebKit/PerformanceTests/Bindings/resources/worker.js
new file mode 100644
index 0000000..1a9fc2f
--- /dev/null
+++ b/third_party/WebKit/PerformanceTests/Bindings/resources/worker.js
@@ -0,0 +1,3 @@
+self.onmessage = function(m) {
+    self.postMessage('received');
+};
diff --git a/third_party/WebKit/PerformanceTests/Bindings/serialize-array.html b/third_party/WebKit/PerformanceTests/Bindings/serialize-array.html
new file mode 100644
index 0000000..f447c71
--- /dev/null
+++ b/third_party/WebKit/PerformanceTests/Bindings/serialize-array.html
@@ -0,0 +1,22 @@
+<!DOCTYPE html>
+<body>
+<script src="../resources/runner.js"></script>
+<script>
+
+var length = 1000000;
+var obj = [];
+for (var i = 0; i < length; i++)
+    obj.push(undefined);
+var worker = new Worker('resources/worker.js');
+worker.onmessage = function(event) {
+    console.log("received");
+};
+
+PerfTestRunner.measureTime({
+    description: "Measures performance of serializing a long array containing 'undefined's.",
+    run: function() {
+        worker.postMessage(obj);
+    }
+});
+</script>
+</body>
diff --git a/third_party/WebKit/PerformanceTests/Bindings/serialize-long-string.html b/third_party/WebKit/PerformanceTests/Bindings/serialize-long-string.html
new file mode 100644
index 0000000..6018a386
--- /dev/null
+++ b/third_party/WebKit/PerformanceTests/Bindings/serialize-long-string.html
@@ -0,0 +1,22 @@
+<!DOCTYPE html>
+<body>
+<script src="../resources/runner.js"></script>
+<script>
+
+var log2Length = 23;
+var str = "a";
+for (var i = 0; i < log2Length; i++)
+    str = str + str;
+var worker = new Worker('resources/worker.js');
+worker.onmessage = function(event) {
+    console.log("received");
+};
+
+PerfTestRunner.measureTime({
+    description: "Measures performance of serializing a long string.",
+    run: function() {
+        worker.postMessage(str);
+    }
+});
+</script>
+</body>
diff --git a/third_party/WebKit/PerformanceTests/Bindings/serialize-map.html b/third_party/WebKit/PerformanceTests/Bindings/serialize-map.html
new file mode 100644
index 0000000..ec498c5
--- /dev/null
+++ b/third_party/WebKit/PerformanceTests/Bindings/serialize-map.html
@@ -0,0 +1,22 @@
+<!DOCTYPE html>
+<body>
+<script src="../resources/runner.js"></script>
+<script>
+
+var length = 200000;
+var obj = {};  // obj does not have a 'length' property.
+for (var i = 0; i < length; i++)
+    obj['key' + i] = i;
+var worker = new Worker('resources/worker.js');
+worker.onmessage = function(event) {
+    console.log("received");
+};
+
+PerfTestRunner.measureTime({
+    description: "Measures performance of serializing a large map object.",
+    run: function() {
+        worker.postMessage(obj);
+    }
+});
+</script>
+</body>
diff --git a/third_party/WebKit/PerformanceTests/Bindings/serialize-nested-array.html b/third_party/WebKit/PerformanceTests/Bindings/serialize-nested-array.html
new file mode 100644
index 0000000..d5757cb0
--- /dev/null
+++ b/third_party/WebKit/PerformanceTests/Bindings/serialize-nested-array.html
@@ -0,0 +1,22 @@
+<!DOCTYPE html>
+<body>
+<script src="../resources/runner.js"></script>
+<script>
+
+var length = 10000;
+var obj = [];
+for (var i = 0; i < length; i++)
+    obj = [obj];
+var worker = new Worker('resources/worker.js');
+worker.onmessage = function(event) {
+    console.log("received");
+};
+
+PerfTestRunner.measureTime({
+    description: "Measures performance of serializing a long chaining nested array.",
+    run: function() {
+        worker.postMessage(obj);
+    }
+});
+</script>
+</body>
diff --git a/third_party/WebKit/Source/bindings/core/v8/RetainedDOMInfo.cpp b/third_party/WebKit/Source/bindings/core/v8/RetainedDOMInfo.cpp
index b150850..59dfe51 100644
--- a/third_party/WebKit/Source/bindings/core/v8/RetainedDOMInfo.cpp
+++ b/third_party/WebKit/Source/bindings/core/v8/RetainedDOMInfo.cpp
@@ -78,12 +78,12 @@
 
 const char* RetainedDOMInfo::GetGroupLabel()
 {
-    return m_root->inDocument() ? "(Document DOM trees)" : "(Detached DOM trees)";
+    return m_root->inShadowIncludingDocument() ? "(Document DOM trees)" : "(Detached DOM trees)";
 }
 
 const char* RetainedDOMInfo::GetLabel()
 {
-    return m_root->inDocument() ? "Document DOM tree" : "Detached DOM tree";
+    return m_root->inShadowIncludingDocument() ? "Document DOM tree" : "Detached DOM tree";
 }
 
 intptr_t RetainedDOMInfo::GetElementCount()
diff --git a/third_party/WebKit/Source/bindings/core/v8/ScriptController.cpp b/third_party/WebKit/Source/bindings/core/v8/ScriptController.cpp
index 771e66a..8d80828 100644
--- a/third_party/WebKit/Source/bindings/core/v8/ScriptController.cpp
+++ b/third_party/WebKit/Source/bindings/core/v8/ScriptController.cpp
@@ -135,7 +135,7 @@
 v8::Local<v8::Value> ScriptController::executeScriptAndReturnValue(v8::Local<v8::Context> context, const ScriptSourceCode& source, AccessControlStatus accessControlStatus, double* compilationFinishTime)
 {
     TRACE_EVENT1("devtools.timeline", "EvaluateScript", "data", InspectorEvaluateScriptEvent::data(frame(), source.url().getString(), source.startPosition()));
-    InspectorInstrumentation::willEvaluateScript(frame()->document());
+    InspectorInstrumentation::allowNativeBreakpoint(frame()->document(), "scriptFirstStatement", false);
 
     v8::Local<v8::Value> result;
     {
diff --git a/third_party/WebKit/Source/bindings/core/v8/V8GCController.cpp b/third_party/WebKit/Source/bindings/core/v8/V8GCController.cpp
index 3430ea4..4307080 100644
--- a/third_party/WebKit/Source/bindings/core/v8/V8GCController.cpp
+++ b/third_party/WebKit/Source/bindings/core/v8/V8GCController.cpp
@@ -78,7 +78,7 @@
 Node* V8GCController::opaqueRootForGC(v8::Isolate*, Node* node)
 {
     ASSERT(node);
-    if (node->inDocument()) {
+    if (node->inShadowIncludingDocument()) {
         Document& document = node->document();
         if (HTMLImportsController* controller = document.importsController())
             return controller->master();
diff --git a/third_party/WebKit/Source/bindings/core/v8/WorkerOrWorkletScriptController.cpp b/third_party/WebKit/Source/bindings/core/v8/WorkerOrWorkletScriptController.cpp
index 1a60161..8b55d51 100644
--- a/third_party/WebKit/Source/bindings/core/v8/WorkerOrWorkletScriptController.cpp
+++ b/third_party/WebKit/Source/bindings/core/v8/WorkerOrWorkletScriptController.cpp
@@ -244,7 +244,7 @@
     return ScriptValue(m_scriptState.get(), result);
 }
 
-bool WorkerOrWorkletScriptController::evaluate(const ScriptSourceCode& sourceCode, RawPtr<ErrorEvent>* errorEvent, CachedMetadataHandler* cacheHandler, V8CacheOptions v8CacheOptions)
+bool WorkerOrWorkletScriptController::evaluate(const ScriptSourceCode& sourceCode, ErrorEvent** errorEvent, CachedMetadataHandler* cacheHandler, V8CacheOptions v8CacheOptions)
 {
     if (isExecutionForbidden())
         return false;
@@ -264,7 +264,7 @@
                 *errorEvent = ErrorEvent::createSanitizedError(m_world.get());
             else
                 *errorEvent = ErrorEvent::create(state.errorMessage, state.sourceURL, state.lineNumber, state.columnNumber, m_world.get());
-            V8ErrorHandler::storeExceptionOnErrorEventWrapper(m_scriptState.get(), errorEvent->get(), state.exception.v8Value(), m_scriptState->context()->Global());
+            V8ErrorHandler::storeExceptionOnErrorEventWrapper(m_scriptState.get(), *errorEvent, state.exception.v8Value(), m_scriptState->context()->Global());
         } else {
             ASSERT(!m_globalScope->shouldSanitizeScriptError(state.sourceURL, NotSharableCrossOrigin));
             RawPtr<ErrorEvent> event = nullptr;
diff --git a/third_party/WebKit/Source/bindings/core/v8/WorkerOrWorkletScriptController.h b/third_party/WebKit/Source/bindings/core/v8/WorkerOrWorkletScriptController.h
index 76b01df..7f0ad02 100644
--- a/third_party/WebKit/Source/bindings/core/v8/WorkerOrWorkletScriptController.h
+++ b/third_party/WebKit/Source/bindings/core/v8/WorkerOrWorkletScriptController.h
@@ -62,7 +62,7 @@
     bool isExecutionTerminating() const;
 
     // Returns true if the evaluation completed with no uncaught exception.
-    bool evaluate(const ScriptSourceCode&, RawPtr<ErrorEvent>* = nullptr, CachedMetadataHandler* = nullptr, V8CacheOptions = V8CacheOptionsDefault);
+    bool evaluate(const ScriptSourceCode&, ErrorEvent** = nullptr, CachedMetadataHandler* = nullptr, V8CacheOptions = V8CacheOptionsDefault);
 
     // Prevents future JavaScript execution. See
     // willScheduleExecutionTermination, isExecutionForbidden.
diff --git a/third_party/WebKit/Source/core/animation/CSSLengthInterpolationType.cpp b/third_party/WebKit/Source/core/animation/CSSLengthInterpolationType.cpp
index 48532bb..6addd0d 100644
--- a/third_party/WebKit/Source/core/animation/CSSLengthInterpolationType.cpp
+++ b/third_party/WebKit/Source/core/animation/CSSLengthInterpolationType.cpp
@@ -292,7 +292,7 @@
     for (size_t i = 0; i < CSSPrimitiveValue::LengthUnitTypeCount; i++) {
         double value = toInterpolableNumber(values.get(i))->value();
         if (value || (i == CSSPrimitiveValue::UnitTypePercentage && hasPercentage)) {
-            RawPtr<CSSCalcExpressionNode> node = CSSCalcValue::createExpressionNode(CSSPrimitiveValue::create(value, toUnitType(i)));
+            CSSCalcExpressionNode* node = CSSCalcValue::createExpressionNode(CSSPrimitiveValue::create(value, toUnitType(i)));
             result = result ? CSSCalcValue::createExpressionNode(result, node, CalcAdd) : node;
         }
     }
diff --git a/third_party/WebKit/Source/core/animation/CSSNumberInterpolationType.cpp b/third_party/WebKit/Source/core/animation/CSSNumberInterpolationType.cpp
index 33187151..fe5b328 100644
--- a/third_party/WebKit/Source/core/animation/CSSNumberInterpolationType.cpp
+++ b/third_party/WebKit/Source/core/animation/CSSNumberInterpolationType.cpp
@@ -83,7 +83,7 @@
 {
     double clampedNumber = NumberPropertyFunctions::clampNumber(cssProperty(), toInterpolableNumber(interpolableValue).value());
     if (!NumberPropertyFunctions::setNumber(cssProperty(), *environment.state().style(), clampedNumber))
-        StyleBuilder::applyProperty(cssProperty(), environment.state(), CSSPrimitiveValue::create(clampedNumber, CSSPrimitiveValue::UnitType::Number).get());
+        StyleBuilder::applyProperty(cssProperty(), environment.state(), CSSPrimitiveValue::create(clampedNumber, CSSPrimitiveValue::UnitType::Number));
 }
 
 } // namespace blink
diff --git a/third_party/WebKit/Source/core/animation/KeyframeEffectModelTest.cpp b/third_party/WebKit/Source/core/animation/KeyframeEffectModelTest.cpp
index d58beee5b..17c05b2 100644
--- a/third_party/WebKit/Source/core/animation/KeyframeEffectModelTest.cpp
+++ b/third_party/WebKit/Source/core/animation/KeyframeEffectModelTest.cpp
@@ -43,7 +43,7 @@
 
 PassRefPtr<AnimatableValue> unknownAnimatableValue(double n)
 {
-    return AnimatableUnknown::create(CSSPrimitiveValue::create(n, CSSPrimitiveValue::UnitType::Unknown).get());
+    return AnimatableUnknown::create(CSSPrimitiveValue::create(n, CSSPrimitiveValue::UnitType::Unknown));
 }
 
 PassRefPtr<AnimatableValue> pixelAnimatableValue(double n)
diff --git a/third_party/WebKit/Source/core/animation/animatable/AnimatableValueTestHelperTest.cpp b/third_party/WebKit/Source/core/animation/animatable/AnimatableValueTestHelperTest.cpp
index fe7541d..52c43094 100644
--- a/third_party/WebKit/Source/core/animation/animatable/AnimatableValueTestHelperTest.cpp
+++ b/third_party/WebKit/Source/core/animation/animatable/AnimatableValueTestHelperTest.cpp
@@ -53,7 +53,7 @@
 TEST_F(AnimationAnimatableValueTestHelperTest, PrintTo)
 {
     EXPECT_THAT(
-        PrintToString(AnimatableClipPathOperation::create(ShapeClipPathOperation::create(BasicShapeCircle::create().get()).get())),
+        PrintToString(AnimatableClipPathOperation::create(ShapeClipPathOperation::create(BasicShapeCircle::create()).get())),
         testing::StartsWith("AnimatableClipPathOperation")
         );
 
@@ -66,7 +66,7 @@
         testing::StartsWith("AnimatableNeutral@"));
 
     EXPECT_THAT(
-        PrintToString(AnimatableShapeValue::create(ShapeValue::createShapeValue(BasicShapeCircle::create().get(), ContentBox))),
+        PrintToString(AnimatableShapeValue::create(ShapeValue::createShapeValue(BasicShapeCircle::create(), ContentBox))),
         testing::StartsWith("AnimatableShapeValue@"));
 
     RefPtr<SVGDashArray> l2 = SVGDashArray::create();
@@ -78,7 +78,7 @@
 
     EXPECT_EQ(
         ::std::string("AnimatableUnknown(none)"),
-        PrintToString(AnimatableUnknown::create(CSSPrimitiveValue::createIdentifier(CSSValueNone).get())));
+        PrintToString(AnimatableUnknown::create(CSSPrimitiveValue::createIdentifier(CSSValueNone))));
 
     EXPECT_EQ(
         ::std::string("AnimatableVisibility(VISIBLE)"),
diff --git a/third_party/WebKit/Source/core/clipboard/DataTransfer.cpp b/third_party/WebKit/Source/core/clipboard/DataTransfer.cpp
index bbf5db59..c31ff3a 100644
--- a/third_party/WebKit/Source/core/clipboard/DataTransfer.cpp
+++ b/third_party/WebKit/Source/core/clipboard/DataTransfer.cpp
@@ -217,7 +217,7 @@
         return;
 
     IntPoint location(x, y);
-    if (isHTMLImageElement(*image) && !image->inDocument())
+    if (isHTMLImageElement(*image) && !image->inShadowIncludingDocument())
         setDragImageResource(toHTMLImageElement(*image).cachedImage(), location);
     else
         setDragImageElement(image, location);
diff --git a/third_party/WebKit/Source/core/core.gypi b/third_party/WebKit/Source/core/core.gypi
index 27aa462..60cee51 100644
--- a/third_party/WebKit/Source/core/core.gypi
+++ b/third_party/WebKit/Source/core/core.gypi
@@ -1600,6 +1600,8 @@
             'editing/state_machines/BackspaceStateMachine.h',
             'editing/state_machines/BackwardGraphemeBoundaryStateMachine.cpp',
             'editing/state_machines/BackwardGraphemeBoundaryStateMachine.h',
+            'editing/state_machines/ForwardGraphemeBoundaryStateMachine.cpp',
+            'editing/state_machines/ForwardGraphemeBoundaryStateMachine.h',
             'editing/state_machines/TextSegmentationMachineState.cpp',
             'editing/state_machines/TextSegmentationMachineState.h',
             'editing/state_machines/StateMachineUtil.cpp',
@@ -3972,6 +3974,7 @@
             'editing/spellcheck/SpellCheckerTest.cpp',
             'editing/state_machines/BackspaceStateMachineTest.cpp',
             'editing/state_machines/BackwardGraphemeBoundaryStateMachineTest.cpp',
+            'editing/state_machines/ForwardGraphemeBoundaryStateMachineTest.cpp',
             'editing/state_machines/StateMachineTestUtil.cpp',
             'editing/state_machines/StateMachineUtilTest.cpp',
             'events/EventPathTest.cpp',
diff --git a/third_party/WebKit/Source/core/css/BasicShapeFunctions.cpp b/third_party/WebKit/Source/core/css/BasicShapeFunctions.cpp
index 1e40b52..0fbfb869 100644
--- a/third_party/WebKit/Source/core/css/BasicShapeFunctions.cpp
+++ b/third_party/WebKit/Source/core/css/BasicShapeFunctions.cpp
@@ -39,7 +39,7 @@
 
 namespace blink {
 
-static RawPtr<CSSValue> valueForCenterCoordinate(CSSValuePool& pool, const ComputedStyle& style, const BasicShapeCenterCoordinate& center, EBoxOrient orientation)
+static CSSValue* valueForCenterCoordinate(CSSValuePool& pool, const ComputedStyle& style, const BasicShapeCenterCoordinate& center, EBoxOrient orientation)
 {
     if (center.getDirection() == BasicShapeCenterCoordinate::TopLeft)
         return pool.createValue(center.length(), style);
@@ -49,7 +49,7 @@
     return CSSValuePair::create(pool.createIdentifierValue(keyword), pool.createValue(center.length(), style), CSSValuePair::DropIdenticalValues);
 }
 
-static RawPtr<CSSPrimitiveValue> basicShapeRadiusToCSSValue(CSSValuePool& pool, const ComputedStyle& style, const BasicShapeRadius& radius)
+static CSSPrimitiveValue* basicShapeRadiusToCSSValue(CSSValuePool& pool, const ComputedStyle& style, const BasicShapeRadius& radius)
 {
     switch (radius.type()) {
     case BasicShapeRadius::Value:
@@ -64,43 +64,43 @@
     return nullptr;
 }
 
-RawPtr<CSSValue> valueForBasicShape(const ComputedStyle& style, const BasicShape* basicShape)
+CSSValue* valueForBasicShape(const ComputedStyle& style, const BasicShape* basicShape)
 {
     CSSValuePool& pool = cssValuePool();
     switch (basicShape->type()) {
     case BasicShape::BasicShapeCircleType: {
         const BasicShapeCircle* circle = toBasicShapeCircle(basicShape);
-        RawPtr<CSSBasicShapeCircleValue> circleValue = CSSBasicShapeCircleValue::create();
+        CSSBasicShapeCircleValue* circleValue = CSSBasicShapeCircleValue::create();
 
         circleValue->setCenterX(valueForCenterCoordinate(pool, style, circle->centerX(), HORIZONTAL));
         circleValue->setCenterY(valueForCenterCoordinate(pool, style, circle->centerY(), VERTICAL));
         circleValue->setRadius(basicShapeRadiusToCSSValue(pool, style, circle->radius()));
-        return circleValue.release();
+        return circleValue;
     }
     case BasicShape::BasicShapeEllipseType: {
         const BasicShapeEllipse* ellipse = toBasicShapeEllipse(basicShape);
-        RawPtr<CSSBasicShapeEllipseValue> ellipseValue = CSSBasicShapeEllipseValue::create();
+        CSSBasicShapeEllipseValue* ellipseValue = CSSBasicShapeEllipseValue::create();
 
         ellipseValue->setCenterX(valueForCenterCoordinate(pool, style, ellipse->centerX(), HORIZONTAL));
         ellipseValue->setCenterY(valueForCenterCoordinate(pool, style, ellipse->centerY(), VERTICAL));
         ellipseValue->setRadiusX(basicShapeRadiusToCSSValue(pool, style, ellipse->radiusX()));
         ellipseValue->setRadiusY(basicShapeRadiusToCSSValue(pool, style, ellipse->radiusY()));
-        return ellipseValue.release();
+        return ellipseValue;
     }
     case BasicShape::BasicShapePolygonType: {
         const BasicShapePolygon* polygon = toBasicShapePolygon(basicShape);
-        RawPtr<CSSBasicShapePolygonValue> polygonValue = CSSBasicShapePolygonValue::create();
+        CSSBasicShapePolygonValue* polygonValue = CSSBasicShapePolygonValue::create();
 
         polygonValue->setWindRule(polygon->getWindRule());
         const Vector<Length>& values = polygon->values();
         for (unsigned i = 0; i < values.size(); i += 2)
             polygonValue->appendPoint(pool.createValue(values.at(i), style), pool.createValue(values.at(i + 1), style));
 
-        return polygonValue.release();
+        return polygonValue;
     }
     case BasicShape::BasicShapeInsetType: {
         const BasicShapeInset* inset = toBasicShapeInset(basicShape);
-        RawPtr<CSSBasicShapeInsetValue> insetValue = CSSBasicShapeInsetValue::create();
+        CSSBasicShapeInsetValue* insetValue = CSSBasicShapeInsetValue::create();
 
         insetValue->setTop(pool.createValue(inset->top(), style));
         insetValue->setRight(pool.createValue(inset->right(), style));
@@ -112,7 +112,7 @@
         insetValue->setBottomRightRadius(CSSValuePair::create(inset->bottomRightRadius(), style));
         insetValue->setBottomLeftRadius(CSSValuePair::create(inset->bottomLeftRadius(), style));
 
-        return insetValue.release();
+        return insetValue;
     }
     default:
         return nullptr;
@@ -173,7 +173,7 @@
     return BasicShapeCenterCoordinate(direction, offset);
 }
 
-static BasicShapeRadius cssValueToBasicShapeRadius(const StyleResolverState& state, RawPtr<CSSPrimitiveValue> radius)
+static BasicShapeRadius cssValueToBasicShapeRadius(const StyleResolverState& state, CSSPrimitiveValue* radius)
 {
     if (!radius)
         return BasicShapeRadius(BasicShapeRadius::ClosestSide);
@@ -190,7 +190,7 @@
         }
     }
 
-    return BasicShapeRadius(convertToLength(state, radius.get()));
+    return BasicShapeRadius(convertToLength(state, radius));
 }
 
 PassRefPtr<BasicShape> basicShapeForValue(const StyleResolverState& state, const CSSValue& basicShapeValue)
diff --git a/third_party/WebKit/Source/core/css/BasicShapeFunctions.h b/third_party/WebKit/Source/core/css/BasicShapeFunctions.h
index 9c3807b7..4a2bbd5 100644
--- a/third_party/WebKit/Source/core/css/BasicShapeFunctions.h
+++ b/third_party/WebKit/Source/core/css/BasicShapeFunctions.h
@@ -43,7 +43,7 @@
 class StyleResolverState;
 class ComputedStyle;
 
-RawPtr<CSSValue> valueForBasicShape(const ComputedStyle&, const BasicShape*);
+CSSValue* valueForBasicShape(const ComputedStyle&, const BasicShape*);
 PassRefPtr<BasicShape> basicShapeForValue(const StyleResolverState&, const CSSValue&);
 FloatPoint floatPointForCenterCoordinate(const BasicShapeCenterCoordinate&, const BasicShapeCenterCoordinate&, FloatSize);
 
diff --git a/third_party/WebKit/Source/core/css/CSSBasicShapeValues.cpp b/third_party/WebKit/Source/core/css/CSSBasicShapeValues.cpp
index 1008e9d..3644286 100644
--- a/third_party/WebKit/Source/core/css/CSSBasicShapeValues.cpp
+++ b/third_party/WebKit/Source/core/css/CSSBasicShapeValues.cpp
@@ -68,15 +68,15 @@
     return offset.cssText();
 }
 
-static RawPtr<CSSValuePair> buildSerializablePositionOffset(RawPtr<CSSValue> offset, CSSValueID defaultSide)
+static CSSValuePair* buildSerializablePositionOffset(CSSValue* offset, CSSValueID defaultSide)
 {
     CSSValueID side = defaultSide;
-    RawPtr<CSSPrimitiveValue> amount = nullptr;
+    CSSPrimitiveValue* amount = nullptr;
 
     if (!offset) {
         side = CSSValueCenter;
-    } else if (offset->isPrimitiveValue() && toCSSPrimitiveValue(offset.get())->isValueID()) {
-        side = toCSSPrimitiveValue(offset.get())->getValueID();
+    } else if (offset->isPrimitiveValue() && toCSSPrimitiveValue(offset)->isValueID()) {
+        side = toCSSPrimitiveValue(offset)->getValueID();
     } else if (offset->isValuePair()) {
         side = toCSSPrimitiveValue(toCSSValuePair(*offset).first()).getValueID();
         amount = &toCSSPrimitiveValue(toCSSValuePair(*offset).second());
@@ -85,7 +85,7 @@
             amount = cssValuePool().createValue(100 - amount->getFloatValue(), CSSPrimitiveValue::UnitType::Percentage);
         }
     } else {
-        amount = toCSSPrimitiveValue(offset.get());
+        amount = toCSSPrimitiveValue(offset);
     }
 
     if (side == CSSValueCenter) {
@@ -99,13 +99,13 @@
         side = defaultSide;
     }
 
-    return CSSValuePair::create(cssValuePool().createIdentifierValue(side), amount.release(), CSSValuePair::KeepIdenticalValues);
+    return CSSValuePair::create(cssValuePool().createIdentifierValue(side), amount, CSSValuePair::KeepIdenticalValues);
 }
 
 String CSSBasicShapeCircleValue::customCSSText() const
 {
-    RawPtr<CSSValuePair> normalizedCX = buildSerializablePositionOffset(m_centerX, CSSValueLeft);
-    RawPtr<CSSValuePair> normalizedCY = buildSerializablePositionOffset(m_centerY, CSSValueTop);
+    CSSValuePair* normalizedCX = buildSerializablePositionOffset(m_centerX, CSSValueLeft);
+    CSSValuePair* normalizedCY = buildSerializablePositionOffset(m_centerY, CSSValueTop);
 
     String radius;
     if (m_radius && m_radius->getValueID() != CSSValueClosestSide)
@@ -164,8 +164,8 @@
 
 String CSSBasicShapeEllipseValue::customCSSText() const
 {
-    RawPtr<CSSValuePair> normalizedCX = buildSerializablePositionOffset(m_centerX, CSSValueLeft);
-    RawPtr<CSSValuePair> normalizedCY = buildSerializablePositionOffset(m_centerY, CSSValueTop);
+    CSSValuePair* normalizedCX = buildSerializablePositionOffset(m_centerX, CSSValueLeft);
+    CSSValuePair* normalizedCY = buildSerializablePositionOffset(m_centerY, CSSValueTop);
 
     String radiusX;
     String radiusY;
diff --git a/third_party/WebKit/Source/core/css/CSSBasicShapeValues.h b/third_party/WebKit/Source/core/css/CSSBasicShapeValues.h
index 107e2e7..0cd6741 100644
--- a/third_party/WebKit/Source/core/css/CSSBasicShapeValues.h
+++ b/third_party/WebKit/Source/core/css/CSSBasicShapeValues.h
@@ -42,7 +42,7 @@
 
 class CSSBasicShapeCircleValue final : public CSSValue {
 public:
-    static RawPtr<CSSBasicShapeCircleValue> create() { return new CSSBasicShapeCircleValue; }
+    static CSSBasicShapeCircleValue* create() { return new CSSBasicShapeCircleValue; }
 
     String customCSSText() const;
     bool equals(const CSSBasicShapeCircleValue&) const;
@@ -52,9 +52,9 @@
     CSSPrimitiveValue* radius() const { return m_radius.get(); }
 
     // TODO(sashab): Remove these and pass them as arguments in the constructor.
-    void setCenterX(RawPtr<CSSValue> centerX) { m_centerX = centerX; }
-    void setCenterY(RawPtr<CSSValue> centerY) { m_centerY = centerY; }
-    void setRadius(RawPtr<CSSPrimitiveValue> radius) { m_radius = radius; }
+    void setCenterX(CSSValue* centerX) { m_centerX = centerX; }
+    void setCenterY(CSSValue* centerY) { m_centerY = centerY; }
+    void setRadius(CSSPrimitiveValue* radius) { m_radius = radius; }
 
     DECLARE_TRACE_AFTER_DISPATCH();
 
@@ -70,7 +70,7 @@
 
 class CSSBasicShapeEllipseValue final : public CSSValue {
 public:
-    static RawPtr<CSSBasicShapeEllipseValue> create() { return new CSSBasicShapeEllipseValue; }
+    static CSSBasicShapeEllipseValue* create() { return new CSSBasicShapeEllipseValue; }
 
     String customCSSText() const;
     bool equals(const CSSBasicShapeEllipseValue&) const;
@@ -81,10 +81,10 @@
     CSSPrimitiveValue* radiusY() const { return m_radiusY.get(); }
 
     // TODO(sashab): Remove these and pass them as arguments in the constructor.
-    void setCenterX(RawPtr<CSSValue> centerX) { m_centerX = centerX; }
-    void setCenterY(RawPtr<CSSValue> centerY) { m_centerY = centerY; }
-    void setRadiusX(RawPtr<CSSPrimitiveValue> radiusX) { m_radiusX = radiusX; }
-    void setRadiusY(RawPtr<CSSPrimitiveValue> radiusY) { m_radiusY = radiusY; }
+    void setCenterX(CSSValue* centerX) { m_centerX = centerX; }
+    void setCenterY(CSSValue* centerY) { m_centerY = centerY; }
+    void setRadiusX(CSSPrimitiveValue* radiusX) { m_radiusX = radiusX; }
+    void setRadiusY(CSSPrimitiveValue* radiusY) { m_radiusY = radiusY; }
 
     DECLARE_TRACE_AFTER_DISPATCH();
 
@@ -101,16 +101,16 @@
 
 class CSSBasicShapePolygonValue final : public CSSValue {
 public:
-    static RawPtr<CSSBasicShapePolygonValue> create() { return new CSSBasicShapePolygonValue; }
+    static CSSBasicShapePolygonValue* create() { return new CSSBasicShapePolygonValue; }
 
-    void appendPoint(RawPtr<CSSPrimitiveValue> x, RawPtr<CSSPrimitiveValue> y)
+    void appendPoint(CSSPrimitiveValue* x, CSSPrimitiveValue* y)
     {
         m_values.append(x);
         m_values.append(y);
     }
 
-    RawPtr<CSSPrimitiveValue> getXAt(unsigned i) const { return m_values.at(i * 2); }
-    RawPtr<CSSPrimitiveValue> getYAt(unsigned i) const { return m_values.at(i * 2 + 1); }
+    CSSPrimitiveValue* getXAt(unsigned i) const { return m_values.at(i * 2); }
+    CSSPrimitiveValue* getYAt(unsigned i) const { return m_values.at(i * 2 + 1); }
     const HeapVector<Member<CSSPrimitiveValue>>& values() const { return m_values; }
 
     // TODO(sashab): Remove this and pass it as an argument in the constructor.
@@ -134,7 +134,7 @@
 
 class CSSBasicShapeInsetValue final : public CSSValue {
 public:
-    static RawPtr<CSSBasicShapeInsetValue> create() { return new CSSBasicShapeInsetValue; }
+    static CSSBasicShapeInsetValue* create() { return new CSSBasicShapeInsetValue; }
 
     CSSPrimitiveValue* top() const { return m_top.get(); }
     CSSPrimitiveValue* right() const { return m_right.get(); }
@@ -147,10 +147,10 @@
     CSSValuePair* bottomLeftRadius() const { return m_bottomLeftRadius.get(); }
 
     // TODO(sashab): Remove these and pass them as arguments in the constructor.
-    void setTop(RawPtr<CSSPrimitiveValue> top) { m_top = top; }
-    void setRight(RawPtr<CSSPrimitiveValue> right) { m_right = right; }
-    void setBottom(RawPtr<CSSPrimitiveValue> bottom) { m_bottom = bottom; }
-    void setLeft(RawPtr<CSSPrimitiveValue> left) { m_left = left; }
+    void setTop(CSSPrimitiveValue* top) { m_top = top; }
+    void setRight(CSSPrimitiveValue* right) { m_right = right; }
+    void setBottom(CSSPrimitiveValue* bottom) { m_bottom = bottom; }
+    void setLeft(CSSPrimitiveValue* left) { m_left = left; }
 
     void updateShapeSize4Values(CSSPrimitiveValue* top, CSSPrimitiveValue* right, CSSPrimitiveValue* bottom, CSSPrimitiveValue* left)
     {
@@ -175,10 +175,10 @@
         updateShapeSize4Values(value1, value2, value3, value2);
     }
 
-    void setTopLeftRadius(RawPtr<CSSValuePair> radius) { m_topLeftRadius = radius; }
-    void setTopRightRadius(RawPtr<CSSValuePair> radius) { m_topRightRadius = radius; }
-    void setBottomRightRadius(RawPtr<CSSValuePair> radius) { m_bottomRightRadius = radius; }
-    void setBottomLeftRadius(RawPtr<CSSValuePair> radius) { m_bottomLeftRadius = radius; }
+    void setTopLeftRadius(CSSValuePair* radius) { m_topLeftRadius = radius; }
+    void setTopRightRadius(CSSValuePair* radius) { m_topRightRadius = radius; }
+    void setBottomRightRadius(CSSValuePair* radius) { m_bottomRightRadius = radius; }
+    void setBottomLeftRadius(CSSValuePair* radius) { m_bottomLeftRadius = radius; }
 
     String customCSSText() const;
     bool equals(const CSSBasicShapeInsetValue&) const;
diff --git a/third_party/WebKit/Source/core/css/CSSBorderImage.cpp b/third_party/WebKit/Source/core/css/CSSBorderImage.cpp
index 59717db..f090435 100644
--- a/third_party/WebKit/Source/core/css/CSSBorderImage.cpp
+++ b/third_party/WebKit/Source/core/css/CSSBorderImage.cpp
@@ -21,15 +21,15 @@
 
 namespace blink {
 
-RawPtr<CSSValueList> createBorderImageValue(RawPtr<CSSValue> image, RawPtr<CSSValue> imageSlice,
-    RawPtr<CSSValue> borderSlice, RawPtr<CSSValue> outset, RawPtr<CSSValue> repeat)
+CSSValueList* createBorderImageValue(CSSValue* image, CSSValue* imageSlice,
+    CSSValue* borderSlice, CSSValue* outset, CSSValue* repeat)
 {
-    RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    CSSValueList* list = CSSValueList::createSpaceSeparated();
     if (image)
         list->append(image);
 
     if (borderSlice || outset) {
-        RawPtr<CSSValueList> listSlash = CSSValueList::createSlashSeparated();
+        CSSValueList* listSlash = CSSValueList::createSlashSeparated();
         if (imageSlice)
             listSlash->append(imageSlice);
 
@@ -45,7 +45,7 @@
     }
     if (repeat)
         list->append(repeat);
-    return list.release();
+    return list;
 }
 
 } // namespace blink
diff --git a/third_party/WebKit/Source/core/css/CSSBorderImage.h b/third_party/WebKit/Source/core/css/CSSBorderImage.h
index da1a179..369165d 100644
--- a/third_party/WebKit/Source/core/css/CSSBorderImage.h
+++ b/third_party/WebKit/Source/core/css/CSSBorderImage.h
@@ -26,8 +26,8 @@
 
 namespace blink {
 
-RawPtr<CSSValueList> createBorderImageValue(RawPtr<CSSValue> image, RawPtr<CSSValue> imageSlice, RawPtr<CSSValue> borderSlice,
-    RawPtr<CSSValue> outset, RawPtr<CSSValue> repeat);
+CSSValueList* createBorderImageValue(CSSValue* image, CSSValue* imageSlice, CSSValue* borderSlice,
+    CSSValue* outset, CSSValue* repeat);
 
 } // namespace blink
 
diff --git a/third_party/WebKit/Source/core/css/CSSBorderImageSliceValue.cpp b/third_party/WebKit/Source/core/css/CSSBorderImageSliceValue.cpp
index cb7018b..6453296 100644
--- a/third_party/WebKit/Source/core/css/CSSBorderImageSliceValue.cpp
+++ b/third_party/WebKit/Source/core/css/CSSBorderImageSliceValue.cpp
@@ -29,7 +29,7 @@
 
 namespace blink {
 
-CSSBorderImageSliceValue::CSSBorderImageSliceValue(RawPtr<CSSQuadValue> slices, bool fill)
+CSSBorderImageSliceValue::CSSBorderImageSliceValue(CSSQuadValue* slices, bool fill)
     : CSSValue(BorderImageSliceClass)
     , m_slices(slices)
     , m_fill(fill)
diff --git a/third_party/WebKit/Source/core/css/CSSBorderImageSliceValue.h b/third_party/WebKit/Source/core/css/CSSBorderImageSliceValue.h
index 3329b58..24ba0c9 100644
--- a/third_party/WebKit/Source/core/css/CSSBorderImageSliceValue.h
+++ b/third_party/WebKit/Source/core/css/CSSBorderImageSliceValue.h
@@ -34,7 +34,7 @@
 
 class CSSBorderImageSliceValue : public CSSValue {
 public:
-    static RawPtr<CSSBorderImageSliceValue> create(RawPtr<CSSQuadValue> slices, bool fill)
+    static CSSBorderImageSliceValue* create(CSSQuadValue* slices, bool fill)
     {
         return new CSSBorderImageSliceValue(slices, fill);
     }
@@ -49,7 +49,7 @@
     DECLARE_TRACE_AFTER_DISPATCH();
 
 private:
-    CSSBorderImageSliceValue(RawPtr<CSSQuadValue> slices, bool fill);
+    CSSBorderImageSliceValue(CSSQuadValue* slices, bool fill);
 
     // These four values are used to make "cuts" in the border image. They can be numbers
     // or percentages.
diff --git a/third_party/WebKit/Source/core/css/CSSCalculationValue.cpp b/third_party/WebKit/Source/core/css/CSSCalculationValue.cpp
index c7e37527..7f01ce0c 100644
--- a/third_party/WebKit/Source/core/css/CSSCalculationValue.cpp
+++ b/third_party/WebKit/Source/core/css/CSSCalculationValue.cpp
@@ -173,16 +173,16 @@
 class CSSCalcPrimitiveValue final : public CSSCalcExpressionNode {
 public:
 
-    static RawPtr<CSSCalcPrimitiveValue> create(RawPtr<CSSPrimitiveValue> value, bool isInteger)
+    static CSSCalcPrimitiveValue* create(CSSPrimitiveValue* value, bool isInteger)
     {
         return new CSSCalcPrimitiveValue(value, isInteger);
     }
 
-    static RawPtr<CSSCalcPrimitiveValue> create(double value, CSSPrimitiveValue::UnitType type, bool isInteger)
+    static CSSCalcPrimitiveValue* create(double value, CSSPrimitiveValue::UnitType type, bool isInteger)
     {
         if (std::isnan(value) || std::isinf(value))
             return nullptr;
-        return new CSSCalcPrimitiveValue(CSSPrimitiveValue::create(value, type).get(), isInteger);
+        return new CSSCalcPrimitiveValue(CSSPrimitiveValue::create(value, type), isInteger);
     }
 
     bool isZero() const override
@@ -267,7 +267,7 @@
     }
 
 private:
-    CSSCalcPrimitiveValue(RawPtr<CSSPrimitiveValue> value, bool isInteger)
+    CSSCalcPrimitiveValue(CSSPrimitiveValue* value, bool isInteger)
         : CSSCalcExpressionNode(unitCategory(value->typeWithCalcResolved()), isInteger)
         , m_value(value)
     {
@@ -324,7 +324,7 @@
 
 class CSSCalcBinaryOperation final : public CSSCalcExpressionNode {
 public:
-    static RawPtr<CSSCalcExpressionNode> create(RawPtr<CSSCalcExpressionNode> leftSide, RawPtr<CSSCalcExpressionNode> rightSide, CalcOperator op)
+    static CSSCalcExpressionNode* create(CSSCalcExpressionNode* leftSide, CSSCalcExpressionNode* rightSide, CalcOperator op)
     {
         ASSERT(leftSide->category() != CalcOther && rightSide->category() != CalcOther);
 
@@ -335,13 +335,13 @@
         return new CSSCalcBinaryOperation(leftSide, rightSide, op, newCategory);
     }
 
-    static RawPtr<CSSCalcExpressionNode> createSimplified(RawPtr<CSSCalcExpressionNode> leftSide, RawPtr<CSSCalcExpressionNode> rightSide, CalcOperator op)
+    static CSSCalcExpressionNode* createSimplified(CSSCalcExpressionNode* leftSide, CSSCalcExpressionNode* rightSide, CalcOperator op)
     {
         CalculationCategory leftCategory = leftSide->category();
         CalculationCategory rightCategory = rightSide->category();
         ASSERT(leftCategory != CalcOther && rightCategory != CalcOther);
 
-        bool isInteger = isIntegerResult(leftSide.get(), rightSide.get(), op);
+        bool isInteger = isIntegerResult(leftSide, rightSide, op);
 
         // Simplify numbers.
         if (leftCategory == CalcNumber && rightCategory == CalcNumber) {
@@ -370,12 +370,12 @@
         } else {
             // Simplify multiplying or dividing by a number for simplifiable types.
             ASSERT(op == CalcMultiply || op == CalcDivide);
-            CSSCalcExpressionNode* numberSide = getNumberSide(leftSide.get(), rightSide.get());
+            CSSCalcExpressionNode* numberSide = getNumberSide(leftSide, rightSide);
             if (!numberSide)
                 return create(leftSide, rightSide, op);
             if (numberSide == leftSide && op == CalcDivide)
                 return nullptr;
-            CSSCalcExpressionNode* otherSide = leftSide == numberSide ? rightSide.get() : leftSide.get();
+            CSSCalcExpressionNode* otherSide = leftSide == numberSide ? rightSide : leftSide;
 
             double number = numberSide->doubleValue();
             if (std::isnan(number) || std::isinf(number))
@@ -534,8 +534,8 @@
     }
 
 private:
-    CSSCalcBinaryOperation(RawPtr<CSSCalcExpressionNode> leftSide, RawPtr<CSSCalcExpressionNode> rightSide, CalcOperator op, CalculationCategory category)
-        : CSSCalcExpressionNode(category, isIntegerResult(leftSide.get(), rightSide.get(), op))
+    CSSCalcBinaryOperation(CSSCalcExpressionNode* leftSide, CSSCalcExpressionNode* rightSide, CalcOperator op, CalculationCategory category)
+        : CSSCalcExpressionNode(category, isIntegerResult(leftSide, rightSide, op))
         , m_leftSide(leftSide)
         , m_rightSide(rightSide)
         , m_operator(op)
@@ -591,7 +591,7 @@
 class CSSCalcExpressionNodeParser {
     STACK_ALLOCATED();
 public:
-    RawPtr<CSSCalcExpressionNode> parseCalc(CSSParserTokenRange tokens)
+    CSSCalcExpressionNode* parseCalc(CSSParserTokenRange tokens)
     {
         Value result;
         tokens.consumeWhitespace();
@@ -709,17 +709,17 @@
     }
 };
 
-RawPtr<CSSCalcExpressionNode> CSSCalcValue::createExpressionNode(RawPtr<CSSPrimitiveValue> value, bool isInteger)
+CSSCalcExpressionNode* CSSCalcValue::createExpressionNode(CSSPrimitiveValue* value, bool isInteger)
 {
     return CSSCalcPrimitiveValue::create(value, isInteger);
 }
 
-RawPtr<CSSCalcExpressionNode> CSSCalcValue::createExpressionNode(RawPtr<CSSCalcExpressionNode> leftSide, RawPtr<CSSCalcExpressionNode> rightSide, CalcOperator op)
+CSSCalcExpressionNode* CSSCalcValue::createExpressionNode(CSSCalcExpressionNode* leftSide, CSSCalcExpressionNode* rightSide, CalcOperator op)
 {
     return CSSCalcBinaryOperation::create(leftSide, rightSide, op);
 }
 
-RawPtr<CSSCalcExpressionNode> CSSCalcValue::createExpressionNode(double pixels, double percent)
+CSSCalcExpressionNode* CSSCalcValue::createExpressionNode(double pixels, double percent)
 {
     return createExpressionNode(
         createExpressionNode(CSSPrimitiveValue::create(pixels, CSSPrimitiveValue::UnitType::Pixels), pixels == trunc(pixels)),
@@ -727,15 +727,15 @@
         CalcAdd);
 }
 
-RawPtr<CSSCalcValue> CSSCalcValue::create(const CSSParserTokenRange& tokens, ValueRange range)
+CSSCalcValue* CSSCalcValue::create(const CSSParserTokenRange& tokens, ValueRange range)
 {
     CSSCalcExpressionNodeParser parser;
-    RawPtr<CSSCalcExpressionNode> expression = parser.parseCalc(tokens);
+    CSSCalcExpressionNode* expression = parser.parseCalc(tokens);
 
     return expression ? new CSSCalcValue(expression, range) : nullptr;
 }
 
-RawPtr<CSSCalcValue> CSSCalcValue::create(RawPtr<CSSCalcExpressionNode> expression, ValueRange range)
+CSSCalcValue* CSSCalcValue::create(CSSCalcExpressionNode* expression, ValueRange range)
 {
     return new CSSCalcValue(expression, range);
 }
diff --git a/third_party/WebKit/Source/core/css/CSSCalculationValue.h b/third_party/WebKit/Source/core/css/CSSCalculationValue.h
index 5a0feaae..5d6df4a7 100644
--- a/third_party/WebKit/Source/core/css/CSSCalculationValue.h
+++ b/third_party/WebKit/Source/core/css/CSSCalculationValue.h
@@ -101,12 +101,12 @@
 
 class CORE_EXPORT CSSCalcValue : public GarbageCollected<CSSCalcValue> {
 public:
-    static RawPtr<CSSCalcValue> create(const CSSParserTokenRange&, ValueRange);
-    static RawPtr<CSSCalcValue> create(RawPtr<CSSCalcExpressionNode>, ValueRange = ValueRangeAll);
+    static CSSCalcValue* create(const CSSParserTokenRange&, ValueRange);
+    static CSSCalcValue* create(CSSCalcExpressionNode*, ValueRange = ValueRangeAll);
 
-    static RawPtr<CSSCalcExpressionNode> createExpressionNode(RawPtr<CSSPrimitiveValue>, bool isInteger = false);
-    static RawPtr<CSSCalcExpressionNode> createExpressionNode(RawPtr<CSSCalcExpressionNode>, RawPtr<CSSCalcExpressionNode>, CalcOperator);
-    static RawPtr<CSSCalcExpressionNode> createExpressionNode(double pixels, double percent);
+    static CSSCalcExpressionNode* createExpressionNode(CSSPrimitiveValue*, bool isInteger = false);
+    static CSSCalcExpressionNode* createExpressionNode(CSSCalcExpressionNode*, CSSCalcExpressionNode*, CalcOperator);
+    static CSSCalcExpressionNode* createExpressionNode(double pixels, double percent);
 
     PassRefPtr<CalculationValue> toCalcValue(const CSSToLengthConversionData& conversionData) const
     {
@@ -132,7 +132,7 @@
     }
 
 private:
-    CSSCalcValue(RawPtr<CSSCalcExpressionNode> expression, ValueRange range)
+    CSSCalcValue(CSSCalcExpressionNode* expression, ValueRange range)
         : m_expression(expression)
         , m_nonNegative(range == ValueRangeNonNegative)
     {
diff --git a/third_party/WebKit/Source/core/css/CSSCalculationValueTest.cpp b/third_party/WebKit/Source/core/css/CSSCalculationValueTest.cpp
index e1262d13..bb0eaaa 100644
--- a/third_party/WebKit/Source/core/css/CSSCalculationValueTest.cpp
+++ b/third_party/WebKit/Source/core/css/CSSCalculationValueTest.cpp
@@ -47,7 +47,7 @@
 
 namespace {
 
-void testAccumulatePixelsAndPercent(const CSSToLengthConversionData& conversionData, RawPtr<CSSCalcExpressionNode> expression, float expectedPixels, float expectedPercent)
+void testAccumulatePixelsAndPercent(const CSSToLengthConversionData& conversionData, CSSCalcExpressionNode* expression, float expectedPixels, float expectedPercent)
 {
     PixelsAndPercent value(0, 0);
     expression->accumulatePixelsAndPercent(conversionData, value);
@@ -65,9 +65,9 @@
 CSSLengthArray& setLengthArray(CSSLengthArray& lengthArray, String text)
 {
     initLengthArray(lengthArray);
-    RawPtr<MutableStylePropertySet> propertySet = MutableStylePropertySet::create(HTMLQuirksMode);
+    MutableStylePropertySet* propertySet = MutableStylePropertySet::create(HTMLQuirksMode);
     propertySet->setProperty(CSSPropertyLeft, text);
-    toCSSPrimitiveValue(propertySet->getPropertyCSSValue(CSSPropertyLeft).get())->accumulateLengthArray(lengthArray);
+    toCSSPrimitiveValue(propertySet->getPropertyCSSValue(CSSPropertyLeft))->accumulateLengthArray(lengthArray);
     return lengthArray;
 }
 
diff --git a/third_party/WebKit/Source/core/css/CSSColorValue.h b/third_party/WebKit/Source/core/css/CSSColorValue.h
index 21e6f518..f6f25f29 100644
--- a/third_party/WebKit/Source/core/css/CSSColorValue.h
+++ b/third_party/WebKit/Source/core/css/CSSColorValue.h
@@ -14,7 +14,7 @@
 // Represents the non-keyword subset of <color>.
 class CSSColorValue : public CSSValue {
 public:
-    static RawPtr<CSSColorValue> create(Color color)
+    static CSSColorValue* create(Color color)
     {
         return new CSSColorValue(color);
     }
diff --git a/third_party/WebKit/Source/core/css/CSSComputedStyleDeclaration.cpp b/third_party/WebKit/Source/core/css/CSSComputedStyleDeclaration.cpp
index 952f98e..8dda6ec 100644
--- a/third_party/WebKit/Source/core/css/CSSComputedStyleDeclaration.cpp
+++ b/third_party/WebKit/Source/core/css/CSSComputedStyleDeclaration.cpp
@@ -349,7 +349,7 @@
     return properties;
 }
 
-CSSComputedStyleDeclaration::CSSComputedStyleDeclaration(RawPtr<Node> n, bool allowVisitedStyle, const String& pseudoElementName)
+CSSComputedStyleDeclaration::CSSComputedStyleDeclaration(Node* n, bool allowVisitedStyle, const String& pseudoElementName)
     : m_node(n)
     , m_allowVisitedStyle(allowVisitedStyle)
 #if !ENABLE(OILPAN)
@@ -408,12 +408,12 @@
     return static_cast<CSSValueID>(CSSValueXxSmall + keywordSize - 1);
 }
 
-inline static RawPtr<CSSPrimitiveValue> zoomAdjustedPixelValue(double value, const ComputedStyle& style)
+inline static CSSPrimitiveValue* zoomAdjustedPixelValue(double value, const ComputedStyle& style)
 {
     return cssValuePool().createValue(adjustFloatForAbsoluteZoom(value, style), CSSPrimitiveValue::UnitType::Pixels);
 }
 
-RawPtr<CSSValue> CSSComputedStyleDeclaration::getFontSizeCSSValuePreferringKeyword() const
+CSSValue* CSSComputedStyleDeclaration::getFontSizeCSSValuePreferringKeyword() const
 {
     if (!m_node)
         return nullptr;
@@ -526,7 +526,7 @@
     return m_node.get();
 }
 
-RawPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(AtomicString customPropertyName) const
+CSSValue* CSSComputedStyleDeclaration::getPropertyCSSValue(AtomicString customPropertyName) const
 {
     const ComputedStyle* style = computeComputedStyle();
     if (!style)
@@ -542,7 +542,7 @@
     return ComputedStyleCSSValueMapping::getVariables(*style);
 }
 
-RawPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropertyID propertyID) const
+CSSValue* CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropertyID propertyID) const
 {
     Node* styledNode = this->styledNode();
     if (!styledNode)
@@ -575,7 +575,7 @@
     if (!style)
         return nullptr;
 
-    RawPtr<CSSValue> value = ComputedStyleCSSValueMapping::get(propertyID, *style, layoutObject, styledNode, m_allowVisitedStyle);
+    CSSValue* value = ComputedStyleCSSValueMapping::get(propertyID, *style, layoutObject, styledNode, m_allowVisitedStyle);
     if (value)
         return value;
 
@@ -585,7 +585,7 @@
 
 String CSSComputedStyleDeclaration::getPropertyValue(CSSPropertyID propertyID) const
 {
-    RawPtr<CSSValue> value = getPropertyCSSValue(propertyID);
+    CSSValue* value = getPropertyCSSValue(propertyID);
     if (value)
         return value->cssText();
     return "";
@@ -619,23 +619,23 @@
                 return true;
         }
     }
-    RawPtr<CSSValue> value = getPropertyCSSValue(propertyID);
+    CSSValue* value = getPropertyCSSValue(propertyID);
     return value && propertyValue && value->equals(*propertyValue);
 }
 
-RawPtr<MutableStylePropertySet> CSSComputedStyleDeclaration::copyProperties() const
+MutableStylePropertySet* CSSComputedStyleDeclaration::copyProperties() const
 {
     return copyPropertiesInSet(computableProperties());
 }
 
-RawPtr<MutableStylePropertySet> CSSComputedStyleDeclaration::copyPropertiesInSet(const Vector<CSSPropertyID>& properties) const
+MutableStylePropertySet* CSSComputedStyleDeclaration::copyPropertiesInSet(const Vector<CSSPropertyID>& properties) const
 {
     HeapVector<CSSProperty, 256> list;
     list.reserveInitialCapacity(properties.size());
     for (unsigned i = 0; i < properties.size(); ++i) {
-        RawPtr<CSSValue> value = getPropertyCSSValue(properties[i]);
+        CSSValue* value = getPropertyCSSValue(properties[i]);
         if (value)
-            list.append(CSSProperty(properties[i], value.release(), false));
+            list.append(CSSProperty(properties[i], value, false));
     }
     return MutableStylePropertySet::create(list.data(), list.size());
 }
@@ -650,7 +650,7 @@
     CSSPropertyID propertyID = cssPropertyID(propertyName);
     if (!propertyID) {
         if (RuntimeEnabledFeatures::cssVariablesEnabled() && CSSVariableParser::isValidVariableName(propertyName)) {
-            RawPtr<CSSValue> value = getPropertyCSSValue(AtomicString(propertyName));
+            CSSValue* value = getPropertyCSSValue(AtomicString(propertyName));
             if (value)
                 return value->cssText();
         }
@@ -687,7 +687,7 @@
     return String();
 }
 
-RawPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValueInternal(CSSPropertyID propertyID)
+CSSValue* CSSComputedStyleDeclaration::getPropertyCSSValueInternal(CSSPropertyID propertyID)
 {
     return getPropertyCSSValue(propertyID);
 }
diff --git a/third_party/WebKit/Source/core/css/CSSComputedStyleDeclaration.h b/third_party/WebKit/Source/core/css/CSSComputedStyleDeclaration.h
index d17d52af..91a9ce0f 100644
--- a/third_party/WebKit/Source/core/css/CSSComputedStyleDeclaration.h
+++ b/third_party/WebKit/Source/core/css/CSSComputedStyleDeclaration.h
@@ -47,7 +47,7 @@
 
 class CORE_EXPORT CSSComputedStyleDeclaration final : public CSSStyleDeclaration {
 public:
-    static RawPtr<CSSComputedStyleDeclaration> create(RawPtr<Node> node, bool allowVisitedStyle = false, const String& pseudoElementName = String())
+    static CSSComputedStyleDeclaration* create(Node* node, bool allowVisitedStyle = false, const String& pseudoElementName = String())
     {
         return new CSSComputedStyleDeclaration(node, allowVisitedStyle, pseudoElementName);
     }
@@ -61,21 +61,21 @@
     String getPropertyValue(CSSPropertyID) const;
     bool getPropertyPriority(CSSPropertyID) const;
 
-    RawPtr<MutableStylePropertySet> copyProperties() const;
+    MutableStylePropertySet* copyProperties() const;
 
-    RawPtr<CSSValue> getPropertyCSSValue(CSSPropertyID) const;
-    RawPtr<CSSValue> getPropertyCSSValue(AtomicString customPropertyName) const;
+    CSSValue* getPropertyCSSValue(CSSPropertyID) const;
+    CSSValue* getPropertyCSSValue(AtomicString customPropertyName) const;
     const HashMap<AtomicString, RefPtr<CSSVariableData>>* getVariables() const;
 
-    RawPtr<CSSValue> getFontSizeCSSValuePreferringKeyword() const;
+    CSSValue* getFontSizeCSSValuePreferringKeyword() const;
     bool isMonospaceFont() const;
 
-    RawPtr<MutableStylePropertySet> copyPropertiesInSet(const Vector<CSSPropertyID>&) const;
+    MutableStylePropertySet* copyPropertiesInSet(const Vector<CSSPropertyID>&) const;
 
     DECLARE_VIRTUAL_TRACE();
 
 private:
-    CSSComputedStyleDeclaration(RawPtr<Node>, bool allowVisitedStyle, const String&);
+    CSSComputedStyleDeclaration(Node*, bool allowVisitedStyle, const String&);
 
     // The styled node is either the node passed into getComputedStyle, or the
     // PseudoElement for :before and :after if they exist.
@@ -99,7 +99,7 @@
     void setCSSFloat(const String&, ExceptionState&);
     String cssText() const override;
     void setCSSText(const String&, ExceptionState&) override;
-    RawPtr<CSSValue> getPropertyCSSValueInternal(CSSPropertyID) override;
+    CSSValue* getPropertyCSSValueInternal(CSSPropertyID) override;
     String getPropertyValueInternal(CSSPropertyID) override;
     void setPropertyInternal(CSSPropertyID, const String& customPropertyName, const String& value, bool important, ExceptionState&) override;
 
diff --git a/third_party/WebKit/Source/core/css/CSSContentDistributionValue.cpp b/third_party/WebKit/Source/core/css/CSSContentDistributionValue.cpp
index fa7bd819..e27f79e 100644
--- a/third_party/WebKit/Source/core/css/CSSContentDistributionValue.cpp
+++ b/third_party/WebKit/Source/core/css/CSSContentDistributionValue.cpp
@@ -23,7 +23,7 @@
 
 String CSSContentDistributionValue::customCSSText() const
 {
-    RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    CSSValueList* list = CSSValueList::createSpaceSeparated();
 
     if (m_distribution != CSSValueInvalid)
         list->append(distribution());
@@ -32,7 +32,7 @@
     if (m_overflow != CSSValueInvalid)
         list->append(overflow());
 
-    return list.release()->customCSSText();
+    return list->customCSSText();
 }
 
 bool CSSContentDistributionValue::equals(const CSSContentDistributionValue& other) const
diff --git a/third_party/WebKit/Source/core/css/CSSContentDistributionValue.h b/third_party/WebKit/Source/core/css/CSSContentDistributionValue.h
index d6fe0b29..509686f 100644
--- a/third_party/WebKit/Source/core/css/CSSContentDistributionValue.h
+++ b/third_party/WebKit/Source/core/css/CSSContentDistributionValue.h
@@ -13,17 +13,17 @@
 
 class CSSContentDistributionValue : public CSSValue {
 public:
-    static RawPtr<CSSContentDistributionValue> create(CSSValueID distribution, CSSValueID position, CSSValueID overflow)
+    static CSSContentDistributionValue* create(CSSValueID distribution, CSSValueID position, CSSValueID overflow)
     {
         return new CSSContentDistributionValue(distribution, position, overflow);
     }
     ~CSSContentDistributionValue();
 
-    RawPtr<CSSPrimitiveValue> distribution() const { return cssValuePool().createIdentifierValue(m_distribution); }
+    CSSPrimitiveValue* distribution() const { return cssValuePool().createIdentifierValue(m_distribution); }
 
-    RawPtr<CSSPrimitiveValue> position() const { return cssValuePool().createIdentifierValue(m_position); }
+    CSSPrimitiveValue* position() const { return cssValuePool().createIdentifierValue(m_position); }
 
-    RawPtr<CSSPrimitiveValue> overflow() const { return cssValuePool().createIdentifierValue(m_overflow); }
+    CSSPrimitiveValue* overflow() const { return cssValuePool().createIdentifierValue(m_overflow); }
 
     String customCSSText() const;
 
diff --git a/third_party/WebKit/Source/core/css/CSSCounterValue.h b/third_party/WebKit/Source/core/css/CSSCounterValue.h
index fb9c4492..0e4217b 100644
--- a/third_party/WebKit/Source/core/css/CSSCounterValue.h
+++ b/third_party/WebKit/Source/core/css/CSSCounterValue.h
@@ -30,7 +30,7 @@
 
 class CSSCounterValue : public CSSValue {
 public:
-    static RawPtr<CSSCounterValue> create(RawPtr<CSSCustomIdentValue> identifier, RawPtr<CSSPrimitiveValue> listStyle, RawPtr<CSSCustomIdentValue> separator)
+    static CSSCounterValue* create(CSSCustomIdentValue* identifier, CSSPrimitiveValue* listStyle, CSSCustomIdentValue* separator)
     {
         return new CSSCounterValue(identifier, listStyle, separator);
     }
@@ -51,7 +51,7 @@
     DECLARE_TRACE_AFTER_DISPATCH();
 
 private:
-    CSSCounterValue(RawPtr<CSSCustomIdentValue> identifier, RawPtr<CSSPrimitiveValue> listStyle, RawPtr<CSSCustomIdentValue> separator)
+    CSSCounterValue(CSSCustomIdentValue* identifier, CSSPrimitiveValue* listStyle, CSSCustomIdentValue* separator)
         : CSSValue(CounterClass)
         , m_identifier(identifier)
         , m_listStyle(listStyle)
diff --git a/third_party/WebKit/Source/core/css/CSSCrossfadeValue.cpp b/third_party/WebKit/Source/core/css/CSSCrossfadeValue.cpp
index 07a1b59..b70c8c5 100644
--- a/third_party/WebKit/Source/core/css/CSSCrossfadeValue.cpp
+++ b/third_party/WebKit/Source/core/css/CSSCrossfadeValue.cpp
@@ -102,7 +102,7 @@
     return KURL(ParsedURLString, toCSSImageValue(*value).url());
 }
 
-CSSCrossfadeValue::CSSCrossfadeValue(RawPtr<CSSValue> fromValue, RawPtr<CSSValue> toValue, RawPtr<CSSPrimitiveValue> percentageValue)
+CSSCrossfadeValue::CSSCrossfadeValue(CSSValue* fromValue, CSSValue* toValue, CSSPrimitiveValue* percentageValue)
     : CSSImageGeneratorValue(CrossfadeClass)
     , m_fromValue(fromValue)
     , m_toValue(toValue)
@@ -148,15 +148,15 @@
     return result.toString();
 }
 
-RawPtr<CSSCrossfadeValue> CSSCrossfadeValue::valueWithURLsMadeAbsolute()
+CSSCrossfadeValue* CSSCrossfadeValue::valueWithURLsMadeAbsolute()
 {
-    RawPtr<CSSValue> fromValue = m_fromValue;
+    CSSValue* fromValue = m_fromValue;
     if (m_fromValue->isImageValue())
         fromValue = toCSSImageValue(*m_fromValue).valueWithURLMadeAbsolute();
-    RawPtr<CSSValue> toValue = m_toValue;
+    CSSValue* toValue = m_toValue;
     if (m_toValue->isImageValue())
         toValue = toCSSImageValue(*m_toValue).valueWithURLMadeAbsolute();
-    return CSSCrossfadeValue::create(fromValue.release(), toValue.release(), m_percentageValue);
+    return CSSCrossfadeValue::create(fromValue, toValue, m_percentageValue);
 }
 
 IntSize CSSCrossfadeValue::fixedSize(const LayoutObject& layoutObject, const FloatSize& defaultObjectSize)
@@ -200,8 +200,8 @@
 
 void CSSCrossfadeValue::loadSubimages(Document* document)
 {
-    RawPtr<ImageResource> oldCachedFromImage = m_cachedFromImage;
-    RawPtr<ImageResource> oldCachedToImage = m_cachedToImage;
+    ImageResource* oldCachedFromImage = m_cachedFromImage;
+    ImageResource* oldCachedToImage = m_cachedToImage;
 
     m_cachedFromImage = cachedImageForCSSValue(m_fromValue.get(), document);
     m_cachedToImage = cachedImageForCSSValue(m_toValue.get(), document);
diff --git a/third_party/WebKit/Source/core/css/CSSCrossfadeValue.h b/third_party/WebKit/Source/core/css/CSSCrossfadeValue.h
index 74026c8..639eca3 100644
--- a/third_party/WebKit/Source/core/css/CSSCrossfadeValue.h
+++ b/third_party/WebKit/Source/core/css/CSSCrossfadeValue.h
@@ -43,7 +43,7 @@
     friend class CrossfadeSubimageObserverProxy;
     USING_PRE_FINALIZER(CSSCrossfadeValue, dispose);
 public:
-    static RawPtr<CSSCrossfadeValue> create(RawPtr<CSSValue> fromValue, RawPtr<CSSValue> toValue, RawPtr<CSSPrimitiveValue> percentageValue)
+    static CSSCrossfadeValue* create(CSSValue* fromValue, CSSValue* toValue, CSSPrimitiveValue* percentageValue)
     {
         return new CSSCrossfadeValue(fromValue, toValue, percentageValue);
     }
@@ -65,12 +65,12 @@
 
     bool equals(const CSSCrossfadeValue&) const;
 
-    RawPtr<CSSCrossfadeValue> valueWithURLsMadeAbsolute();
+    CSSCrossfadeValue* valueWithURLsMadeAbsolute();
 
     DECLARE_TRACE_AFTER_DISPATCH();
 
 private:
-    CSSCrossfadeValue(RawPtr<CSSValue> fromValue, RawPtr<CSSValue> toValue, RawPtr<CSSPrimitiveValue> percentageValue);
+    CSSCrossfadeValue(CSSValue* fromValue, CSSValue* toValue, CSSPrimitiveValue* percentageValue);
 
     void dispose();
 
diff --git a/third_party/WebKit/Source/core/css/CSSCursorImageValue.cpp b/third_party/WebKit/Source/core/css/CSSCursorImageValue.cpp
index a4d912f..4912942c 100644
--- a/third_party/WebKit/Source/core/css/CSSCursorImageValue.cpp
+++ b/third_party/WebKit/Source/core/css/CSSCursorImageValue.cpp
@@ -42,7 +42,7 @@
     return isSVGCursorElement(element) ? toSVGCursorElement(element) : nullptr;
 }
 
-CSSCursorImageValue::CSSCursorImageValue(RawPtr<CSSValue> imageValue, bool hotSpotSpecified, const IntPoint& hotSpot)
+CSSCursorImageValue::CSSCursorImageValue(CSSValue* imageValue, bool hotSpotSpecified, const IntPoint& hotSpot)
     : CSSValue(CursorImageClass)
     , m_imageValue(imageValue)
     , m_hotSpotSpecified(hotSpotSpecified)
@@ -144,10 +144,10 @@
         // to change the URL of the CSSImageValue (which would then change behavior like cssText),
         // we create an alternate CSSImageValue to use.
         if (isSVGCursor() && document) {
-            RawPtr<CSSImageValue> imageValue = toCSSImageValue(m_imageValue.get());
+            CSSImageValue* imageValue = toCSSImageValue(m_imageValue.get());
             // FIXME: This will fail if the <cursor> element is in a shadow DOM (bug 59827)
             if (SVGCursorElement* cursorElement = resourceReferencedByCursorElement(imageValue->url(), *document)) {
-                RawPtr<CSSImageValue> svgImageValue = CSSImageValue::create(document->completeURL(cursorElement->href()->currentValue()->value()));
+                CSSImageValue* svgImageValue = CSSImageValue::create(document->completeURL(cursorElement->href()->currentValue()->value()));
                 svgImageValue->setReferrer(imageValue->referrer());
                 m_cachedImage = svgImageValue->cacheImage(document);
                 return m_cachedImage.get();
@@ -166,7 +166,7 @@
 bool CSSCursorImageValue::isSVGCursor() const
 {
     if (m_imageValue->isImageValue()) {
-        RawPtr<CSSImageValue> imageValue = toCSSImageValue(m_imageValue.get());
+        CSSImageValue* imageValue = toCSSImageValue(m_imageValue.get());
         KURL kurl(ParsedURLString, imageValue->url());
         return kurl.hasFragmentIdentifier();
     }
diff --git a/third_party/WebKit/Source/core/css/CSSCursorImageValue.h b/third_party/WebKit/Source/core/css/CSSCursorImageValue.h
index e1e8570..7e0f2b3 100644
--- a/third_party/WebKit/Source/core/css/CSSCursorImageValue.h
+++ b/third_party/WebKit/Source/core/css/CSSCursorImageValue.h
@@ -32,7 +32,7 @@
 
 class CSSCursorImageValue : public CSSValue {
 public:
-    static RawPtr<CSSCursorImageValue> create(RawPtr<CSSValue> imageValue, bool hotSpotSpecified, const IntPoint& hotSpot)
+    static CSSCursorImageValue* create(CSSValue* imageValue, bool hotSpotSpecified, const IntPoint& hotSpot)
     {
         return new CSSCursorImageValue(imageValue, hotSpotSpecified, hotSpot);
     }
@@ -59,7 +59,7 @@
     DECLARE_TRACE_AFTER_DISPATCH();
 
 private:
-    CSSCursorImageValue(RawPtr<CSSValue> imageValue, bool hotSpotSpecified, const IntPoint& hotSpot);
+    CSSCursorImageValue(CSSValue* imageValue, bool hotSpotSpecified, const IntPoint& hotSpot);
 
     bool isSVGCursor() const;
     String cachedImageURL();
diff --git a/third_party/WebKit/Source/core/css/CSSCustomIdentValue.h b/third_party/WebKit/Source/core/css/CSSCustomIdentValue.h
index 835eb70..a7768010 100644
--- a/third_party/WebKit/Source/core/css/CSSCustomIdentValue.h
+++ b/third_party/WebKit/Source/core/css/CSSCustomIdentValue.h
@@ -14,13 +14,13 @@
 
 class CSSCustomIdentValue : public CSSValue {
 public:
-    static RawPtr<CSSCustomIdentValue> create(const String& str)
+    static CSSCustomIdentValue* create(const String& str)
     {
         return new CSSCustomIdentValue(str);
     }
 
     // TODO(sashab, timloh): Remove this and lazily parse the CSSPropertyID in isKnownPropertyID().
-    static RawPtr<CSSCustomIdentValue> create(CSSPropertyID id)
+    static CSSCustomIdentValue* create(CSSPropertyID id)
     {
         return new CSSCustomIdentValue(id);
     }
diff --git a/third_party/WebKit/Source/core/css/CSSCustomPropertyDeclaration.h b/third_party/WebKit/Source/core/css/CSSCustomPropertyDeclaration.h
index 392ecf6..c2fcc12 100644
--- a/third_party/WebKit/Source/core/css/CSSCustomPropertyDeclaration.h
+++ b/third_party/WebKit/Source/core/css/CSSCustomPropertyDeclaration.h
@@ -14,12 +14,12 @@
 
 class CSSCustomPropertyDeclaration : public CSSValue {
 public:
-    static RawPtr<CSSCustomPropertyDeclaration> create(const AtomicString& name, PassRefPtr<CSSVariableData> value)
+    static CSSCustomPropertyDeclaration* create(const AtomicString& name, PassRefPtr<CSSVariableData> value)
     {
         return new CSSCustomPropertyDeclaration(name, value);
     }
 
-    static RawPtr<CSSCustomPropertyDeclaration> create(const AtomicString& name, CSSValueID id)
+    static CSSCustomPropertyDeclaration* create(const AtomicString& name, CSSValueID id)
     {
         return new CSSCustomPropertyDeclaration(name, id);
     }
diff --git a/third_party/WebKit/Source/core/css/CSSDefaultStyleSheets.cpp b/third_party/WebKit/Source/core/css/CSSDefaultStyleSheets.cpp
index faeb1f5..2eb90c9 100644
--- a/third_party/WebKit/Source/core/css/CSSDefaultStyleSheets.cpp
+++ b/third_party/WebKit/Source/core/css/CSSDefaultStyleSheets.cpp
@@ -61,14 +61,14 @@
     return staticPrintEval;
 }
 
-static RawPtr<StyleSheetContents> parseUASheet(const String& str)
+static StyleSheetContents* parseUASheet(const String& str)
 {
-    RawPtr<StyleSheetContents> sheet = StyleSheetContents::create(CSSParserContext(UASheetMode, 0));
+    StyleSheetContents* sheet = StyleSheetContents::create(CSSParserContext(UASheetMode, 0));
     sheet->parseString(str);
     // User Agent stylesheets are parsed once for the lifetime of the renderer
     // process and are intentionally leaked.
-    LEAK_SANITIZER_IGNORE_OBJECT(sheet.get());
-    return sheet.release();
+    LEAK_SANITIZER_IGNORE_OBJECT(sheet);
+    return sheet;
 }
 
 CSSDefaultStyleSheets::CSSDefaultStyleSheets()
@@ -107,8 +107,8 @@
     if (!m_defaultViewSourceStyle) {
         m_defaultViewSourceStyle = RuleSet::create();
         // Loaded stylesheet is leaked on purpose.
-        RawPtr<StyleSheetContents> stylesheet = parseUASheet(loadResourceAsASCIIString("view-source.css"));
-        m_defaultViewSourceStyle->addRulesFromSheet(stylesheet.release().leakRef(), screenEval());
+        StyleSheetContents* stylesheet = parseUASheet(loadResourceAsASCIIString("view-source.css"));
+        m_defaultViewSourceStyle->addRulesFromSheet(stylesheet, screenEval());
     }
     return m_defaultViewSourceStyle.get();
 }
@@ -118,8 +118,8 @@
     if (!m_defaultXHTMLMobileProfileStyle) {
         m_defaultXHTMLMobileProfileStyle = RuleSet::create();
         // Loaded stylesheet is leaked on purpose.
-        RawPtr<StyleSheetContents> stylesheet = parseUASheet(loadResourceAsASCIIString("xhtmlmp.css"));
-        m_defaultXHTMLMobileProfileStyle->addRulesFromSheet(stylesheet.release().leakRef(), screenEval());
+        StyleSheetContents* stylesheet = parseUASheet(loadResourceAsASCIIString("xhtmlmp.css"));
+        m_defaultXHTMLMobileProfileStyle->addRulesFromSheet(stylesheet, screenEval());
     }
     return m_defaultXHTMLMobileProfileStyle.get();
 }
diff --git a/third_party/WebKit/Source/core/css/CSSFontFace.cpp b/third_party/WebKit/Source/core/css/CSSFontFace.cpp
index 402d8dd..d9aaf83 100644
--- a/third_party/WebKit/Source/core/css/CSSFontFace.cpp
+++ b/third_party/WebKit/Source/core/css/CSSFontFace.cpp
@@ -37,7 +37,7 @@
 
 namespace blink {
 
-void CSSFontFace::addSource(RawPtr<CSSFontFaceSource> source)
+void CSSFontFace::addSource(CSSFontFaceSource* source)
 {
     source->setFontFace(this);
     m_sources.append(source);
diff --git a/third_party/WebKit/Source/core/css/CSSFontFace.h b/third_party/WebKit/Source/core/css/CSSFontFace.h
index 30dc846..27e16ee31 100644
--- a/third_party/WebKit/Source/core/css/CSSFontFace.h
+++ b/third_party/WebKit/Source/core/css/CSSFontFace.h
@@ -63,7 +63,7 @@
 
     bool isValid() const { return !m_sources.isEmpty(); }
 
-    void addSource(RawPtr<CSSFontFaceSource>);
+    void addSource(CSSFontFaceSource*);
 
     void didBeginLoad();
     void fontLoaded(RemoteFontFaceSource*);
diff --git a/third_party/WebKit/Source/core/css/CSSFontFaceRule.h b/third_party/WebKit/Source/core/css/CSSFontFaceRule.h
index 4b8315b3..5237eab8 100644
--- a/third_party/WebKit/Source/core/css/CSSFontFaceRule.h
+++ b/third_party/WebKit/Source/core/css/CSSFontFaceRule.h
@@ -34,7 +34,7 @@
 class CSSFontFaceRule final : public CSSRule {
     DEFINE_WRAPPERTYPEINFO();
 public:
-    static RawPtr<CSSFontFaceRule> create(StyleRuleFontFace* rule, CSSStyleSheet* sheet)
+    static CSSFontFaceRule* create(StyleRuleFontFace* rule, CSSStyleSheet* sheet)
     {
         return new CSSFontFaceRule(rule, sheet);
     }
diff --git a/third_party/WebKit/Source/core/css/CSSFontFaceSrcValue.cpp b/third_party/WebKit/Source/core/css/CSSFontFaceSrcValue.cpp
index 2703956a..99d39f6 100644
--- a/third_party/WebKit/Source/core/css/CSSFontFaceSrcValue.cpp
+++ b/third_party/WebKit/Source/core/css/CSSFontFaceSrcValue.cpp
@@ -93,10 +93,10 @@
         SecurityOrigin* securityOrigin = document->getSecurityOrigin();
         setCrossOriginAccessControl(request, securityOrigin);
         request.mutableResourceRequest().setHTTPReferrer(SecurityPolicy::generateReferrer(m_referrer.referrerPolicy, request.url(), m_referrer.referrer));
-        RawPtr<FontResource> resource = FontResource::fetch(request, document->fetcher());
+        FontResource* resource = FontResource::fetch(request, document->fetcher());
         if (!resource)
             return nullptr;
-        m_fetched = FontResourceHelper::create(resource.release());
+        m_fetched = FontResourceHelper::create(resource);
     } else {
         // FIXME: CSSFontFaceSrcValue::fetch is invoked when @font-face rule
         // is processed by StyleResolver / StyleEngine.
diff --git a/third_party/WebKit/Source/core/css/CSSFontFaceSrcValue.h b/third_party/WebKit/Source/core/css/CSSFontFaceSrcValue.h
index 6bae02a..fe855ff5a 100644
--- a/third_party/WebKit/Source/core/css/CSSFontFaceSrcValue.h
+++ b/third_party/WebKit/Source/core/css/CSSFontFaceSrcValue.h
@@ -39,11 +39,11 @@
 
 class CSSFontFaceSrcValue : public CSSValue {
 public:
-    static RawPtr<CSSFontFaceSrcValue> create(const String& specifiedResource, const String& absoluteResource, ContentSecurityPolicyDisposition shouldCheckContentSecurityPolicy)
+    static CSSFontFaceSrcValue* create(const String& specifiedResource, const String& absoluteResource, ContentSecurityPolicyDisposition shouldCheckContentSecurityPolicy)
     {
         return new CSSFontFaceSrcValue(specifiedResource, absoluteResource, false, shouldCheckContentSecurityPolicy);
     }
-    static RawPtr<CSSFontFaceSrcValue> createLocal(const String& absoluteResource, ContentSecurityPolicyDisposition shouldCheckContentSecurityPolicy)
+    static CSSFontFaceSrcValue* createLocal(const String& absoluteResource, ContentSecurityPolicyDisposition shouldCheckContentSecurityPolicy)
     {
         return new CSSFontFaceSrcValue(emptyString(), absoluteResource, true, shouldCheckContentSecurityPolicy);
     }
@@ -94,7 +94,7 @@
     class FontResourceHelper : public GarbageCollectedFinalized<FontResourceHelper>, public ResourceOwner<FontResource> {
         USING_GARBAGE_COLLECTED_MIXIN(FontResourceHelper);
     public:
-        static RawPtr<FontResourceHelper> create(RawPtr<FontResource> resource)
+        static FontResourceHelper* create(FontResource* resource)
         {
             return new FontResourceHelper(resource);
         }
@@ -102,7 +102,7 @@
         DEFINE_INLINE_VIRTUAL_TRACE() { ResourceOwner<FontResource>::trace(visitor); }
 
     private:
-        FontResourceHelper(RawPtr<FontResource> resource)
+        FontResourceHelper(FontResource* resource)
         {
             setResource(resource);
         }
diff --git a/third_party/WebKit/Source/core/css/CSSFontFamilyValue.h b/third_party/WebKit/Source/core/css/CSSFontFamilyValue.h
index 4c4286c8..1b557e1 100644
--- a/third_party/WebKit/Source/core/css/CSSFontFamilyValue.h
+++ b/third_party/WebKit/Source/core/css/CSSFontFamilyValue.h
@@ -13,7 +13,7 @@
 
 class CSSFontFamilyValue : public CSSValue {
 public:
-    static RawPtr<CSSFontFamilyValue> create(const String& str)
+    static CSSFontFamilyValue* create(const String& str)
     {
         return new CSSFontFamilyValue(str);
     }
diff --git a/third_party/WebKit/Source/core/css/CSSFontFeatureValue.h b/third_party/WebKit/Source/core/css/CSSFontFeatureValue.h
index 515a5bc..c63597fd 100644
--- a/third_party/WebKit/Source/core/css/CSSFontFeatureValue.h
+++ b/third_party/WebKit/Source/core/css/CSSFontFeatureValue.h
@@ -33,7 +33,7 @@
 
 class CSSFontFeatureValue : public CSSValue {
 public:
-    static RawPtr<CSSFontFeatureValue> create(const AtomicString& tag, int value)
+    static CSSFontFeatureValue* create(const AtomicString& tag, int value)
     {
         return new CSSFontFeatureValue(tag, value);
     }
diff --git a/third_party/WebKit/Source/core/css/CSSFontSelector.h b/third_party/WebKit/Source/core/css/CSSFontSelector.h
index c62fd08..6e169b2b5b 100644
--- a/third_party/WebKit/Source/core/css/CSSFontSelector.h
+++ b/third_party/WebKit/Source/core/css/CSSFontSelector.h
@@ -44,7 +44,7 @@
 
 class CORE_EXPORT CSSFontSelector : public FontSelector {
 public:
-    static RawPtr<CSSFontSelector> create(Document* document)
+    static CSSFontSelector* create(Document* document)
     {
         return new CSSFontSelector(document);
     }
diff --git a/third_party/WebKit/Source/core/css/CSSFunctionValue.h b/third_party/WebKit/Source/core/css/CSSFunctionValue.h
index fbd0142..23b09e21 100644
--- a/third_party/WebKit/Source/core/css/CSSFunctionValue.h
+++ b/third_party/WebKit/Source/core/css/CSSFunctionValue.h
@@ -12,7 +12,7 @@
 
 class CSSFunctionValue : public CSSValueList {
 public:
-    static RawPtr<CSSFunctionValue> create(CSSValueID id)
+    static CSSFunctionValue* create(CSSValueID id)
     {
         return new CSSFunctionValue(id);
     }
diff --git a/third_party/WebKit/Source/core/css/CSSGradientValue.h b/third_party/WebKit/Source/core/css/CSSGradientValue.h
index 182a2cee..78e085d 100644
--- a/third_party/WebKit/Source/core/css/CSSGradientValue.h
+++ b/third_party/WebKit/Source/core/css/CSSGradientValue.h
@@ -88,10 +88,10 @@
 public:
     PassRefPtr<Image> image(const LayoutObject&, const IntSize&);
 
-    void setFirstX(RawPtr<CSSValue> val) { m_firstX = val; }
-    void setFirstY(RawPtr<CSSValue> val) { m_firstY = val; }
-    void setSecondX(RawPtr<CSSValue> val) { m_secondX = val; }
-    void setSecondY(RawPtr<CSSValue> val) { m_secondY = val; }
+    void setFirstX(CSSValue* val) { m_firstX = val; }
+    void setFirstY(CSSValue* val) { m_firstY = val; }
+    void setSecondX(CSSValue* val) { m_secondX = val; }
+    void setSecondY(CSSValue* val) { m_secondY = val; }
 
     void addStop(const CSSGradientColorStop& stop) { m_stops.append(stop); }
 
@@ -151,12 +151,12 @@
 class CSSLinearGradientValue final : public CSSGradientValue {
 public:
 
-    static RawPtr<CSSLinearGradientValue> create(CSSGradientRepeat repeat, CSSGradientType gradientType = CSSLinearGradient)
+    static CSSLinearGradientValue* create(CSSGradientRepeat repeat, CSSGradientType gradientType = CSSLinearGradient)
     {
         return new CSSLinearGradientValue(repeat, gradientType);
     }
 
-    void setAngle(RawPtr<CSSPrimitiveValue> val) { m_angle = val; }
+    void setAngle(CSSPrimitiveValue* val) { m_angle = val; }
 
     String customCSSText() const;
 
@@ -180,21 +180,21 @@
 
 class CSSRadialGradientValue final : public CSSGradientValue {
 public:
-    static RawPtr<CSSRadialGradientValue> create(CSSGradientRepeat repeat, CSSGradientType gradientType = CSSRadialGradient)
+    static CSSRadialGradientValue* create(CSSGradientRepeat repeat, CSSGradientType gradientType = CSSRadialGradient)
     {
         return new CSSRadialGradientValue(repeat, gradientType);
     }
 
     String customCSSText() const;
 
-    void setFirstRadius(RawPtr<CSSPrimitiveValue> val) { m_firstRadius = val; }
-    void setSecondRadius(RawPtr<CSSPrimitiveValue> val) { m_secondRadius = val; }
+    void setFirstRadius(CSSPrimitiveValue* val) { m_firstRadius = val; }
+    void setSecondRadius(CSSPrimitiveValue* val) { m_secondRadius = val; }
 
-    void setShape(RawPtr<CSSPrimitiveValue> val) { m_shape = val; }
-    void setSizingBehavior(RawPtr<CSSPrimitiveValue> val) { m_sizingBehavior = val; }
+    void setShape(CSSPrimitiveValue* val) { m_shape = val; }
+    void setSizingBehavior(CSSPrimitiveValue* val) { m_sizingBehavior = val; }
 
-    void setEndHorizontalSize(RawPtr<CSSPrimitiveValue> val) { m_endHorizontalSize = val; }
-    void setEndVerticalSize(RawPtr<CSSPrimitiveValue> val) { m_endVerticalSize = val; }
+    void setEndHorizontalSize(CSSPrimitiveValue* val) { m_endHorizontalSize = val; }
+    void setEndVerticalSize(CSSPrimitiveValue* val) { m_endVerticalSize = val; }
 
     // Create the gradient for a given size.
     PassRefPtr<Gradient> createGradient(const CSSToLengthConversionData&, const IntSize&, const LayoutObject&);
diff --git a/third_party/WebKit/Source/core/css/CSSGridAutoRepeatValue.h b/third_party/WebKit/Source/core/css/CSSGridAutoRepeatValue.h
index f8074d7..bf23452 100644
--- a/third_party/WebKit/Source/core/css/CSSGridAutoRepeatValue.h
+++ b/third_party/WebKit/Source/core/css/CSSGridAutoRepeatValue.h
@@ -23,7 +23,7 @@
 // allows us to keep the parsing algorithm almost intact.
 class CSSGridAutoRepeatValue : public CSSValueList {
 public:
-    static RawPtr<CSSGridAutoRepeatValue> create(CSSValueID id)
+    static CSSGridAutoRepeatValue* create(CSSValueID id)
     {
         return new CSSGridAutoRepeatValue(id);
     }
diff --git a/third_party/WebKit/Source/core/css/CSSGridLineNamesValue.h b/third_party/WebKit/Source/core/css/CSSGridLineNamesValue.h
index 96e3a30..721b952 100644
--- a/third_party/WebKit/Source/core/css/CSSGridLineNamesValue.h
+++ b/third_party/WebKit/Source/core/css/CSSGridLineNamesValue.h
@@ -38,7 +38,7 @@
 
 class CSSGridLineNamesValue : public CSSValueList {
 public:
-    static RawPtr<CSSGridLineNamesValue> create()
+    static CSSGridLineNamesValue* create()
     {
         return new CSSGridLineNamesValue();
     }
diff --git a/third_party/WebKit/Source/core/css/CSSGridTemplateAreasValue.h b/third_party/WebKit/Source/core/css/CSSGridTemplateAreasValue.h
index 45c6e9e..1a874402 100644
--- a/third_party/WebKit/Source/core/css/CSSGridTemplateAreasValue.h
+++ b/third_party/WebKit/Source/core/css/CSSGridTemplateAreasValue.h
@@ -39,7 +39,7 @@
 
 class CSSGridTemplateAreasValue : public CSSValue {
 public:
-    static RawPtr<CSSGridTemplateAreasValue> create(const NamedGridAreaMap& gridAreaMap, size_t rowCount, size_t columnCount)
+    static CSSGridTemplateAreasValue* create(const NamedGridAreaMap& gridAreaMap, size_t rowCount, size_t columnCount)
     {
         return new CSSGridTemplateAreasValue(gridAreaMap, rowCount, columnCount);
     }
diff --git a/third_party/WebKit/Source/core/css/CSSGroupingRule.cpp b/third_party/WebKit/Source/core/css/CSSGroupingRule.cpp
index 5e8f361b..3afa24e 100644
--- a/third_party/WebKit/Source/core/css/CSSGroupingRule.cpp
+++ b/third_party/WebKit/Source/core/css/CSSGroupingRule.cpp
@@ -69,7 +69,7 @@
 
     CSSStyleSheet* styleSheet = parentStyleSheet();
     CSSParserContext context(parserContext(), UseCounter::getFrom(styleSheet));
-    RawPtr<StyleRuleBase> newRule = CSSParser::parseRule(context, styleSheet ? styleSheet->contents() : nullptr, ruleString);
+    StyleRuleBase* newRule = CSSParser::parseRule(context, styleSheet ? styleSheet->contents() : nullptr, ruleString);
     if (!newRule) {
         exceptionState.throwDOMException(SyntaxError, "the rule '" + ruleString + "' is invalid and cannot be parsed.");
         return 0;
diff --git a/third_party/WebKit/Source/core/css/CSSImageGeneratorValue.cpp b/third_party/WebKit/Source/core/css/CSSImageGeneratorValue.cpp
index be1fc8c..832d0c3 100644
--- a/third_party/WebKit/Source/core/css/CSSImageGeneratorValue.cpp
+++ b/third_party/WebKit/Source/core/css/CSSImageGeneratorValue.cpp
@@ -65,7 +65,7 @@
     }
 }
 
-RawPtr<CSSImageGeneratorValue> CSSImageGeneratorValue::valueWithURLsMadeAbsolute()
+CSSImageGeneratorValue* CSSImageGeneratorValue::valueWithURLsMadeAbsolute()
 {
     if (isCrossfadeValue())
         return toCSSCrossfadeValue(this)->valueWithURLsMadeAbsolute();
@@ -107,7 +107,6 @@
         SizeAndCount& sizeCount = it->value;
         IntSize oldSize = sizeCount.size;
         if (oldSize != size) {
-            RawPtr<CSSImageGeneratorValue> protect(this);
             removeClient(layoutObject);
             addClient(layoutObject, size);
         }
diff --git a/third_party/WebKit/Source/core/css/CSSImageGeneratorValue.h b/third_party/WebKit/Source/core/css/CSSImageGeneratorValue.h
index 345b8253c..6d5b552 100644
--- a/third_party/WebKit/Source/core/css/CSSImageGeneratorValue.h
+++ b/third_party/WebKit/Source/core/css/CSSImageGeneratorValue.h
@@ -69,7 +69,7 @@
 
     void loadSubimages(Document*);
 
-    RawPtr<CSSImageGeneratorValue> valueWithURLsMadeAbsolute();
+    CSSImageGeneratorValue* valueWithURLsMadeAbsolute();
 
     DEFINE_INLINE_TRACE_AFTER_DISPATCH() { CSSValue::traceAfterDispatch(visitor); }
 
diff --git a/third_party/WebKit/Source/core/css/CSSImageSetValue.cpp b/third_party/WebKit/Source/core/css/CSSImageSetValue.cpp
index 43fc1c7..cb4e6f5 100644
--- a/third_party/WebKit/Source/core/css/CSSImageSetValue.cpp
+++ b/third_party/WebKit/Source/core/css/CSSImageSetValue.cpp
@@ -122,8 +122,8 @@
         if (crossOrigin != CrossOriginAttributeNotSet)
             request.setCrossOriginAccessControl(document->getSecurityOrigin(), crossOrigin);
 
-        if (RawPtr<ImageResource> cachedImage = ImageResource::fetch(request, document->fetcher()))
-            m_cachedImage = StyleFetchedImageSet::create(cachedImage.get(), image.scaleFactor, this, request.url());
+        if (ImageResource* cachedImage = ImageResource::fetch(request, document->fetcher()))
+            m_cachedImage = StyleFetchedImageSet::create(cachedImage, image.scaleFactor, this, request.url());
         else
             m_cachedImage = StyleInvalidImage::create(image.imageURL);
         m_cachedScaleFactor = deviceScaleFactor;
@@ -177,12 +177,12 @@
     CSSValueList::traceAfterDispatch(visitor);
 }
 
-RawPtr<CSSImageSetValue> CSSImageSetValue::valueWithURLsMadeAbsolute()
+CSSImageSetValue* CSSImageSetValue::valueWithURLsMadeAbsolute()
 {
-    RawPtr<CSSImageSetValue> value = CSSImageSetValue::create();
+    CSSImageSetValue* value = CSSImageSetValue::create();
     for (auto& item : *this)
         item->isImageValue() ? value->append(toCSSImageValue(*item).valueWithURLMadeAbsolute()) : value->append(item);
-    return value.release();
+    return value;
 }
 
 
diff --git a/third_party/WebKit/Source/core/css/CSSImageSetValue.h b/third_party/WebKit/Source/core/css/CSSImageSetValue.h
index 55e68a02..f5a1cd28 100644
--- a/third_party/WebKit/Source/core/css/CSSImageSetValue.h
+++ b/third_party/WebKit/Source/core/css/CSSImageSetValue.h
@@ -39,7 +39,7 @@
 class CSSImageSetValue : public CSSValueList {
 public:
 
-    static RawPtr<CSSImageSetValue> create()
+    static CSSImageSetValue* create()
     {
         return new CSSImageSetValue();
     }
@@ -58,7 +58,7 @@
         float scaleFactor;
     };
 
-    RawPtr<CSSImageSetValue> valueWithURLsMadeAbsolute();
+    CSSImageSetValue* valueWithURLsMadeAbsolute();
 
     bool hasFailedOrCanceledSubresources() const;
 
diff --git a/third_party/WebKit/Source/core/css/CSSImageValue.cpp b/third_party/WebKit/Source/core/css/CSSImageValue.cpp
index e3ba7dcf..9185fe3f 100644
--- a/third_party/WebKit/Source/core/css/CSSImageValue.cpp
+++ b/third_party/WebKit/Source/core/css/CSSImageValue.cpp
@@ -69,8 +69,8 @@
         if (crossOrigin != CrossOriginAttributeNotSet)
             request.setCrossOriginAccessControl(document->getSecurityOrigin(), crossOrigin);
 
-        if (RawPtr<ImageResource> cachedImage = ImageResource::fetch(request, document->fetcher()))
-            m_cachedImage = StyleFetchedImage::create(cachedImage.get(), document, request.url());
+        if (ImageResource* cachedImage = ImageResource::fetch(request, document->fetcher()))
+            m_cachedImage = StyleFetchedImage::create(cachedImage, document, request.url());
         else
             m_cachedImage = StyleInvalidImage::create(url());
     }
diff --git a/third_party/WebKit/Source/core/css/CSSImageValue.h b/third_party/WebKit/Source/core/css/CSSImageValue.h
index 0082a0e..da38ac2 100644
--- a/third_party/WebKit/Source/core/css/CSSImageValue.h
+++ b/third_party/WebKit/Source/core/css/CSSImageValue.h
@@ -36,19 +36,19 @@
 
 class CORE_EXPORT CSSImageValue : public CSSValue {
 public:
-    static RawPtr<CSSImageValue> create(const KURL& url, StyleImage* image = 0)
+    static CSSImageValue* create(const KURL& url, StyleImage* image = 0)
     {
         return create(url.getString(), url, image);
     }
-    static RawPtr<CSSImageValue> create(const String& rawValue, const KURL& url, StyleImage* image = 0)
+    static CSSImageValue* create(const String& rawValue, const KURL& url, StyleImage* image = 0)
     {
         return create(AtomicString(rawValue), url, image);
     }
-    static RawPtr<CSSImageValue> create(const AtomicString& rawValue, const KURL& url, StyleImage* image = 0)
+    static CSSImageValue* create(const AtomicString& rawValue, const KURL& url, StyleImage* image = 0)
     {
         return new CSSImageValue(rawValue, url, image);
     }
-    static RawPtr<CSSImageValue> create(const AtomicString& absoluteURL)
+    static CSSImageValue* create(const AtomicString& absoluteURL)
     {
         return new CSSImageValue(absoluteURL);
     }
@@ -73,7 +73,7 @@
 
     bool knownToBeOpaque(const LayoutObject&) const;
 
-    RawPtr<CSSImageValue> valueWithURLMadeAbsolute()
+    CSSImageValue* valueWithURLMadeAbsolute()
     {
         return create(KURL(ParsedURLString, m_absoluteURL), m_cachedImage.get());
     }
diff --git a/third_party/WebKit/Source/core/css/CSSImportRule.h b/third_party/WebKit/Source/core/css/CSSImportRule.h
index 90c51b2..0796dc8 100644
--- a/third_party/WebKit/Source/core/css/CSSImportRule.h
+++ b/third_party/WebKit/Source/core/css/CSSImportRule.h
@@ -33,7 +33,7 @@
 class CSSImportRule final : public CSSRule {
     DEFINE_WRAPPERTYPEINFO();
 public:
-    static RawPtr<CSSImportRule> create(StyleRuleImport* rule, CSSStyleSheet* sheet)
+    static CSSImportRule* create(StyleRuleImport* rule, CSSStyleSheet* sheet)
     {
         return new CSSImportRule(rule, sheet);
     }
diff --git a/third_party/WebKit/Source/core/css/CSSInheritedValue.h b/third_party/WebKit/Source/core/css/CSSInheritedValue.h
index 232aff6a..811388ee 100644
--- a/third_party/WebKit/Source/core/css/CSSInheritedValue.h
+++ b/third_party/WebKit/Source/core/css/CSSInheritedValue.h
@@ -28,7 +28,7 @@
 
 class CSSInheritedValue : public CSSValue {
 public:
-    static RawPtr<CSSInheritedValue> create()
+    static CSSInheritedValue* create()
     {
         return new CSSInheritedValue;
     }
diff --git a/third_party/WebKit/Source/core/css/CSSInitialValue.h b/third_party/WebKit/Source/core/css/CSSInitialValue.h
index f86da526..20b1761 100644
--- a/third_party/WebKit/Source/core/css/CSSInitialValue.h
+++ b/third_party/WebKit/Source/core/css/CSSInitialValue.h
@@ -28,11 +28,11 @@
 
 class CSSInitialValue : public CSSValue {
 public:
-    static RawPtr<CSSInitialValue> createExplicit()
+    static CSSInitialValue* createExplicit()
     {
         return new CSSInitialValue(/* implicit */ false);
     }
-    static RawPtr<CSSInitialValue> createImplicit()
+    static CSSInitialValue* createImplicit()
     {
         return new CSSInitialValue(/* implicit */ true);
     }
diff --git a/third_party/WebKit/Source/core/css/CSSKeyframesRule.cpp b/third_party/WebKit/Source/core/css/CSSKeyframesRule.cpp
index 6c80236..3d022d6b 100644
--- a/third_party/WebKit/Source/core/css/CSSKeyframesRule.cpp
+++ b/third_party/WebKit/Source/core/css/CSSKeyframesRule.cpp
@@ -53,14 +53,14 @@
 {
 }
 
-void StyleRuleKeyframes::parserAppendKeyframe(RawPtr<StyleRuleKeyframe> keyframe)
+void StyleRuleKeyframes::parserAppendKeyframe(StyleRuleKeyframe* keyframe)
 {
     if (!keyframe)
         return;
     m_keyframes.append(keyframe);
 }
 
-void StyleRuleKeyframes::wrapperAppendKeyframe(RawPtr<StyleRuleKeyframe> keyframe)
+void StyleRuleKeyframes::wrapperAppendKeyframe(StyleRuleKeyframe* keyframe)
 {
     m_keyframes.append(keyframe);
     styleChanged();
@@ -122,7 +122,7 @@
 
     CSSStyleSheet* styleSheet = parentStyleSheet();
     CSSParserContext context(parserContext(), UseCounter::getFrom(styleSheet));
-    RawPtr<StyleRuleKeyframe> keyframe = CSSParser::parseKeyframeRule(context, ruleText);
+    StyleRuleKeyframe* keyframe = CSSParser::parseKeyframeRule(context, ruleText);
     if (!keyframe)
         return;
 
diff --git a/third_party/WebKit/Source/core/css/CSSKeyframesRule.h b/third_party/WebKit/Source/core/css/CSSKeyframesRule.h
index b723248e..d8ec807 100644
--- a/third_party/WebKit/Source/core/css/CSSKeyframesRule.h
+++ b/third_party/WebKit/Source/core/css/CSSKeyframesRule.h
@@ -39,14 +39,14 @@
 
 class StyleRuleKeyframes final : public StyleRuleBase {
 public:
-    static RawPtr<StyleRuleKeyframes> create() { return new StyleRuleKeyframes(); }
+    static StyleRuleKeyframes* create() { return new StyleRuleKeyframes(); }
 
     ~StyleRuleKeyframes();
 
     const HeapVector<Member<StyleRuleKeyframe>>& keyframes() const { return m_keyframes; }
 
-    void parserAppendKeyframe(RawPtr<StyleRuleKeyframe>);
-    void wrapperAppendKeyframe(RawPtr<StyleRuleKeyframe>);
+    void parserAppendKeyframe(StyleRuleKeyframe*);
+    void wrapperAppendKeyframe(StyleRuleKeyframe*);
     void wrapperRemoveKeyframe(unsigned);
 
     String name() const { return m_name; }
@@ -57,7 +57,7 @@
 
     int findKeyframeIndex(const String& key) const;
 
-    RawPtr<StyleRuleKeyframes> copy() const { return new StyleRuleKeyframes(*this); }
+    StyleRuleKeyframes* copy() const { return new StyleRuleKeyframes(*this); }
 
     DECLARE_TRACE_AFTER_DISPATCH();
 
@@ -79,7 +79,7 @@
 class CSSKeyframesRule final : public CSSRule {
     DEFINE_WRAPPERTYPEINFO();
 public:
-    static RawPtr<CSSKeyframesRule> create(StyleRuleKeyframes* rule, CSSStyleSheet* sheet)
+    static CSSKeyframesRule* create(StyleRuleKeyframes* rule, CSSStyleSheet* sheet)
     {
         return new CSSKeyframesRule(rule, sheet);
     }
diff --git a/third_party/WebKit/Source/core/css/CSSMatrix.cpp b/third_party/WebKit/Source/core/css/CSSMatrix.cpp
index ea9fac2..e1011ae 100644
--- a/third_party/WebKit/Source/core/css/CSSMatrix.cpp
+++ b/third_party/WebKit/Source/core/css/CSSMatrix.cpp
@@ -40,7 +40,7 @@
 
 namespace blink {
 
-RawPtr<CSSMatrix> CSSMatrix::create(ExecutionContext* executionContext, const String& s, ExceptionState& exceptionState)
+CSSMatrix* CSSMatrix::create(ExecutionContext* executionContext, const String& s, ExceptionState& exceptionState)
 {
     UseCounter::count(executionContext, UseCounter::WebKitCSSMatrix);
     return new CSSMatrix(s, exceptionState);
@@ -69,9 +69,9 @@
     if (string.isEmpty())
         return;
 
-    if (RawPtr<CSSValue> value = CSSParser::parseSingleValue(CSSPropertyTransform, string)) {
+    if (CSSValue* value = CSSParser::parseSingleValue(CSSPropertyTransform, string)) {
         // Check for a "none" transform. In these cases we can use the default identity matrix.
-        if (value->isPrimitiveValue() && (toCSSPrimitiveValue(value.get()))->getValueID() == CSSValueNone)
+        if (value->isPrimitiveValue() && (toCSSPrimitiveValue(value))->getValueID() == CSSValueNone)
             return;
 
         DEFINE_STATIC_REF(ComputedStyle, initialStyle, createInitialStyle());
@@ -90,7 +90,7 @@
 }
 
 // Perform a concatenation of the matrices (this * secondMatrix)
-RawPtr<CSSMatrix> CSSMatrix::multiply(CSSMatrix* secondMatrix) const
+CSSMatrix* CSSMatrix::multiply(CSSMatrix* secondMatrix) const
 {
     if (!secondMatrix)
         return nullptr;
@@ -98,7 +98,7 @@
     return CSSMatrix::create(TransformationMatrix(*m_matrix).multiply(*secondMatrix->m_matrix));
 }
 
-RawPtr<CSSMatrix> CSSMatrix::inverse(ExceptionState& exceptionState) const
+CSSMatrix* CSSMatrix::inverse(ExceptionState& exceptionState) const
 {
     if (!m_matrix->isInvertible()) {
         exceptionState.throwDOMException(NotSupportedError, "The matrix is not invertable.");
@@ -108,7 +108,7 @@
     return CSSMatrix::create(m_matrix->inverse());
 }
 
-RawPtr<CSSMatrix> CSSMatrix::translate(double x, double y, double z) const
+CSSMatrix* CSSMatrix::translate(double x, double y, double z) const
 {
     if (std::isnan(x))
         x = 0;
@@ -119,7 +119,7 @@
     return CSSMatrix::create(TransformationMatrix(*m_matrix).translate3d(x, y, z));
 }
 
-RawPtr<CSSMatrix> CSSMatrix::scale(double scaleX, double scaleY, double scaleZ) const
+CSSMatrix* CSSMatrix::scale(double scaleX, double scaleY, double scaleZ) const
 {
     if (std::isnan(scaleX))
         scaleX = 1;
@@ -130,7 +130,7 @@
     return CSSMatrix::create(TransformationMatrix(*m_matrix).scale3d(scaleX, scaleY, scaleZ));
 }
 
-RawPtr<CSSMatrix> CSSMatrix::rotate(double rotX, double rotY, double rotZ) const
+CSSMatrix* CSSMatrix::rotate(double rotX, double rotY, double rotZ) const
 {
     if (std::isnan(rotX))
         rotX = 0;
@@ -148,7 +148,7 @@
     return CSSMatrix::create(TransformationMatrix(*m_matrix).rotate3d(rotX, rotY, rotZ));
 }
 
-RawPtr<CSSMatrix> CSSMatrix::rotateAxisAngle(double x, double y, double z, double angle) const
+CSSMatrix* CSSMatrix::rotateAxisAngle(double x, double y, double z, double angle) const
 {
     if (std::isnan(x))
         x = 0;
@@ -163,14 +163,14 @@
     return CSSMatrix::create(TransformationMatrix(*m_matrix).rotate3d(x, y, z, angle));
 }
 
-RawPtr<CSSMatrix> CSSMatrix::skewX(double angle) const
+CSSMatrix* CSSMatrix::skewX(double angle) const
 {
     if (std::isnan(angle))
         angle = 0;
     return CSSMatrix::create(TransformationMatrix(*m_matrix).skewX(angle));
 }
 
-RawPtr<CSSMatrix> CSSMatrix::skewY(double angle) const
+CSSMatrix* CSSMatrix::skewY(double angle) const
 {
     if (std::isnan(angle))
         angle = 0;
diff --git a/third_party/WebKit/Source/core/css/CSSMatrix.h b/third_party/WebKit/Source/core/css/CSSMatrix.h
index dde2324..c29886ef 100644
--- a/third_party/WebKit/Source/core/css/CSSMatrix.h
+++ b/third_party/WebKit/Source/core/css/CSSMatrix.h
@@ -39,11 +39,11 @@
 class CSSMatrix final : public GarbageCollectedFinalized<CSSMatrix>, public ScriptWrappable {
     DEFINE_WRAPPERTYPEINFO();
 public:
-    static RawPtr<CSSMatrix> create(const TransformationMatrix& m)
+    static CSSMatrix* create(const TransformationMatrix& m)
     {
         return new CSSMatrix(m);
     }
-    static RawPtr<CSSMatrix> create(ExecutionContext*, const String&, ExceptionState&);
+    static CSSMatrix* create(ExecutionContext*, const String&, ExceptionState&);
 
     double a() const { return m_matrix->a(); }
     double b() const { return m_matrix->b(); }
@@ -99,48 +99,48 @@
     // specified operation applied. The this value is not modified.
 
     // Multiply this matrix by secondMatrix, on the right (result = this * secondMatrix)
-    RawPtr<CSSMatrix> multiply(CSSMatrix* secondMatrix) const;
+    CSSMatrix* multiply(CSSMatrix* secondMatrix) const;
 
     // Return the inverse of this matrix. Throw an exception if the matrix is not invertible
-    RawPtr<CSSMatrix> inverse(ExceptionState&) const;
+    CSSMatrix* inverse(ExceptionState&) const;
 
     // Return this matrix translated by the passed values.
     // Passing a NaN will use a value of 0. This allows the 3D form to used for 2D operations
     // Operation is performed as though the this matrix is multiplied by a matrix with
     // the translation values on the left (result = translation(x,y,z) * this)
-    RawPtr<CSSMatrix> translate(double x, double y, double z) const;
+    CSSMatrix* translate(double x, double y, double z) const;
 
     // Returns this matrix scaled by the passed values.
     // Passing scaleX or scaleZ as NaN uses a value of 1, but passing scaleY of NaN
     // makes it the same as scaleX. This allows the 3D form to used for 2D operations
     // Operation is performed as though the this matrix is multiplied by a matrix with
     // the scale values on the left (result = scale(x,y,z) * this)
-    RawPtr<CSSMatrix> scale(double scaleX, double scaleY, double scaleZ) const;
+    CSSMatrix* scale(double scaleX, double scaleY, double scaleZ) const;
 
     // Returns this matrix rotated by the passed values.
     // If rotY and rotZ are NaN, rotate about Z (rotX=0, rotateY=0, rotateZ=rotX).
     // Otherwise use a rotation value of 0 for any passed NaN.
     // Operation is performed as though the this matrix is multiplied by a matrix with
     // the rotation values on the left (result = rotation(x,y,z) * this)
-    RawPtr<CSSMatrix> rotate(double rotX, double rotY, double rotZ) const;
+    CSSMatrix* rotate(double rotX, double rotY, double rotZ) const;
 
     // Returns this matrix rotated about the passed axis by the passed angle.
     // Passing a NaN will use a value of 0. If the axis is (0,0,0) use a value
     // Operation is performed as though the this matrix is multiplied by a matrix with
     // the rotation values on the left (result = rotation(x,y,z,angle) * this)
-    RawPtr<CSSMatrix> rotateAxisAngle(double x, double y, double z, double angle) const;
+    CSSMatrix* rotateAxisAngle(double x, double y, double z, double angle) const;
 
     // Return this matrix skewed along the X axis by the passed values.
     // Passing a NaN will use a value of 0.
     // Operation is performed as though the this matrix is multiplied by a matrix with
     // the skew values on the left (result = skewX(angle) * this)
-    RawPtr<CSSMatrix> skewX(double angle) const;
+    CSSMatrix* skewX(double angle) const;
 
     // Return this matrix skewed along the Y axis by the passed values.
     // Passing a NaN will use a value of 0.
     // Operation is performed as though the this matrix is multiplied by a matrix with
     // the skew values on the left (result = skewY(angle) * this)
-    RawPtr<CSSMatrix> skewY(double angle) const;
+    CSSMatrix* skewY(double angle) const;
 
     const TransformationMatrix& transform() const { return *m_matrix; }
 
diff --git a/third_party/WebKit/Source/core/css/CSSMediaRule.h b/third_party/WebKit/Source/core/css/CSSMediaRule.h
index acd3268..3235f1e6 100644
--- a/third_party/WebKit/Source/core/css/CSSMediaRule.h
+++ b/third_party/WebKit/Source/core/css/CSSMediaRule.h
@@ -33,7 +33,7 @@
 class CSSMediaRule final : public CSSGroupingRule {
     DEFINE_WRAPPERTYPEINFO();
 public:
-    static RawPtr<CSSMediaRule> create(StyleRuleMedia* rule, CSSStyleSheet* sheet)
+    static CSSMediaRule* create(StyleRuleMedia* rule, CSSStyleSheet* sheet)
     {
         return new CSSMediaRule(rule, sheet);
     }
diff --git a/third_party/WebKit/Source/core/css/CSSNamespaceRule.h b/third_party/WebKit/Source/core/css/CSSNamespaceRule.h
index 5048b8e..b8d2acd 100644
--- a/third_party/WebKit/Source/core/css/CSSNamespaceRule.h
+++ b/third_party/WebKit/Source/core/css/CSSNamespaceRule.h
@@ -15,7 +15,7 @@
 class CSSNamespaceRule final : public CSSRule {
     DEFINE_WRAPPERTYPEINFO();
 public:
-    static RawPtr<CSSNamespaceRule> create(StyleRuleNamespace* rule, CSSStyleSheet* sheet)
+    static CSSNamespaceRule* create(StyleRuleNamespace* rule, CSSStyleSheet* sheet)
     {
         return new CSSNamespaceRule(rule, sheet);
     }
diff --git a/third_party/WebKit/Source/core/css/CSSPageRule.h b/third_party/WebKit/Source/core/css/CSSPageRule.h
index 2c903b3..f59f886 100644
--- a/third_party/WebKit/Source/core/css/CSSPageRule.h
+++ b/third_party/WebKit/Source/core/css/CSSPageRule.h
@@ -35,7 +35,7 @@
 class CORE_EXPORT CSSPageRule final : public CSSRule {
     DEFINE_WRAPPERTYPEINFO();
 public:
-    static RawPtr<CSSPageRule> create(StyleRulePage* rule, CSSStyleSheet* sheet)
+    static CSSPageRule* create(StyleRulePage* rule, CSSStyleSheet* sheet)
     {
         return new CSSPageRule(rule, sheet);
     }
diff --git a/third_party/WebKit/Source/core/css/CSSPaintValue.cpp b/third_party/WebKit/Source/core/css/CSSPaintValue.cpp
index 89736c2..c4348e10 100644
--- a/third_party/WebKit/Source/core/css/CSSPaintValue.cpp
+++ b/third_party/WebKit/Source/core/css/CSSPaintValue.cpp
@@ -10,7 +10,7 @@
 
 namespace blink {
 
-CSSPaintValue::CSSPaintValue(RawPtr<CSSCustomIdentValue> name)
+CSSPaintValue::CSSPaintValue(CSSCustomIdentValue* name)
     : CSSImageGeneratorValue(PaintClass)
     , m_name(name)
 {
diff --git a/third_party/WebKit/Source/core/css/CSSPaintValue.h b/third_party/WebKit/Source/core/css/CSSPaintValue.h
index 6aa505cc..dcb25375 100644
--- a/third_party/WebKit/Source/core/css/CSSPaintValue.h
+++ b/third_party/WebKit/Source/core/css/CSSPaintValue.h
@@ -13,7 +13,7 @@
 
 class CSSPaintValue : public CSSImageGeneratorValue {
 public:
-    static RawPtr<CSSPaintValue> create(RawPtr<CSSCustomIdentValue> name)
+    static CSSPaintValue* create(CSSCustomIdentValue* name)
     {
         return new CSSPaintValue(name);
     }
@@ -37,7 +37,7 @@
     DECLARE_TRACE_AFTER_DISPATCH();
 
 private:
-    explicit CSSPaintValue(RawPtr<CSSCustomIdentValue> name);
+    explicit CSSPaintValue(CSSCustomIdentValue* name);
 
     Member<CSSCustomIdentValue> m_name;
 };
diff --git a/third_party/WebKit/Source/core/css/CSSPathValue.cpp b/third_party/WebKit/Source/core/css/CSSPathValue.cpp
index 43421478..78770a3c 100644
--- a/third_party/WebKit/Source/core/css/CSSPathValue.cpp
+++ b/third_party/WebKit/Source/core/css/CSSPathValue.cpp
@@ -9,12 +9,12 @@
 
 namespace blink {
 
-RawPtr<CSSPathValue> CSSPathValue::create(PassRefPtr<StylePath> stylePath)
+CSSPathValue* CSSPathValue::create(PassRefPtr<StylePath> stylePath)
 {
     return new CSSPathValue(stylePath);
 }
 
-RawPtr<CSSPathValue> CSSPathValue::create(PassOwnPtr<SVGPathByteStream> pathByteStream)
+CSSPathValue* CSSPathValue::create(PassOwnPtr<SVGPathByteStream> pathByteStream)
 {
     return CSSPathValue::create(StylePath::create(pathByteStream));
 }
@@ -28,7 +28,7 @@
 
 namespace {
 
-RawPtr<CSSPathValue> createPathValue()
+CSSPathValue* createPathValue()
 {
     OwnPtr<SVGPathByteStream> pathByteStream = SVGPathByteStream::create();
     // Need to be registered as LSan ignored, as it will be reachable and
diff --git a/third_party/WebKit/Source/core/css/CSSPathValue.h b/third_party/WebKit/Source/core/css/CSSPathValue.h
index ca1e03c..99e3e799 100644
--- a/third_party/WebKit/Source/core/css/CSSPathValue.h
+++ b/third_party/WebKit/Source/core/css/CSSPathValue.h
@@ -17,8 +17,8 @@
 
 class CSSPathValue : public CSSValue {
 public:
-    static RawPtr<CSSPathValue> create(PassRefPtr<StylePath>);
-    static RawPtr<CSSPathValue> create(PassOwnPtr<SVGPathByteStream>);
+    static CSSPathValue* create(PassRefPtr<StylePath>);
+    static CSSPathValue* create(PassOwnPtr<SVGPathByteStream>);
 
     static CSSPathValue& emptyPathValue();
 
diff --git a/third_party/WebKit/Source/core/css/CSSPrimitiveValue.cpp b/third_party/WebKit/Source/core/css/CSSPrimitiveValue.cpp
index 51666b6..6883f6a 100644
--- a/third_party/WebKit/Source/core/css/CSSPrimitiveValue.cpp
+++ b/third_party/WebKit/Source/core/css/CSSPrimitiveValue.cpp
@@ -289,11 +289,11 @@
     m_primitiveUnitType = static_cast<unsigned>(type);
 }
 
-void CSSPrimitiveValue::init(RawPtr<CSSCalcValue> c)
+void CSSPrimitiveValue::init(CSSCalcValue* c)
 {
     init(UnitType::Calc);
     m_hasCachedCSSText = false;
-    m_value.calc = c.leakRef();
+    m_value.calc = c;
 }
 
 CSSPrimitiveValue::~CSSPrimitiveValue()
diff --git a/third_party/WebKit/Source/core/css/CSSPrimitiveValue.h b/third_party/WebKit/Source/core/css/CSSPrimitiveValue.h
index bd24534..b6148e73 100644
--- a/third_party/WebKit/Source/core/css/CSSPrimitiveValue.h
+++ b/third_party/WebKit/Source/core/css/CSSPrimitiveValue.h
@@ -200,19 +200,19 @@
     bool isValueID() const { return type() == UnitType::ValueID; }
     bool colorIsDerivedFromElement() const;
 
-    static RawPtr<CSSPrimitiveValue> createIdentifier(CSSValueID valueID)
+    static CSSPrimitiveValue* createIdentifier(CSSValueID valueID)
     {
         return new CSSPrimitiveValue(valueID);
     }
-    static RawPtr<CSSPrimitiveValue> create(double value, UnitType type)
+    static CSSPrimitiveValue* create(double value, UnitType type)
     {
         return new CSSPrimitiveValue(value, type);
     }
-    static RawPtr<CSSPrimitiveValue> create(const Length& value, float zoom)
+    static CSSPrimitiveValue* create(const Length& value, float zoom)
     {
         return new CSSPrimitiveValue(value, zoom);
     }
-    template<typename T> static RawPtr<CSSPrimitiveValue> create(T value)
+    template<typename T> static CSSPrimitiveValue* create(T value)
     {
         static_assert(!std::is_same<T, CSSValueID>::value, "Do not call create() with a CSSValueID; call createIdentifier() instead");
         return new CSSPrimitiveValue(value);
@@ -262,13 +262,8 @@
     CSSPrimitiveValue(double, UnitType);
 
     template<typename T> CSSPrimitiveValue(T); // Defined in CSSPrimitiveValueMappings.h
-    template<typename T> CSSPrimitiveValue(T* val)
-        : CSSValue(PrimitiveClass)
-    {
-        init(RawPtr<T>(val));
-    }
 
-    template<typename T> CSSPrimitiveValue(RawPtr<T> val)
+    template<typename T> CSSPrimitiveValue(T* val)
         : CSSValue(PrimitiveClass)
     {
         init(val);
@@ -280,7 +275,7 @@
 
     void init(UnitType);
     void init(const Length&);
-    void init(RawPtr<CSSCalcValue>);
+    void init(CSSCalcValue*);
 
     double computeLengthDouble(const CSSToLengthConversionData&) const;
 
diff --git a/third_party/WebKit/Source/core/css/CSSProperty.h b/third_party/WebKit/Source/core/css/CSSProperty.h
index d2f2f4f..fb1dc883 100644
--- a/third_party/WebKit/Source/core/css/CSSProperty.h
+++ b/third_party/WebKit/Source/core/css/CSSProperty.h
@@ -58,7 +58,7 @@
 class CSSProperty {
     DISALLOW_NEW_EXCEPT_PLACEMENT_NEW();
 public:
-    CSSProperty(CSSPropertyID propertyID, RawPtr<CSSValue> value, bool important = false, bool isSetFromShorthand = false, int indexInShorthandsVector = 0, bool implicit = false)
+    CSSProperty(CSSPropertyID propertyID, CSSValue* value, bool important = false, bool isSetFromShorthand = false, int indexInShorthandsVector = 0, bool implicit = false)
         : m_metadata(propertyID, isSetFromShorthand, indexInShorthandsVector, important, implicit, CSSPropertyMetadata::isInheritedProperty(propertyID))
         , m_value(value)
     {
diff --git a/third_party/WebKit/Source/core/css/CSSPropertySourceData.h b/third_party/WebKit/Source/core/css/CSSPropertySourceData.h
index d70074a..d151e20 100644
--- a/third_party/WebKit/Source/core/css/CSSPropertySourceData.h
+++ b/third_party/WebKit/Source/core/css/CSSPropertySourceData.h
@@ -70,7 +70,7 @@
 };
 
 struct CSSStyleSourceData : public GarbageCollected<CSSStyleSourceData> {
-    static RawPtr<CSSStyleSourceData> create()
+    static CSSStyleSourceData* create()
     {
         return new CSSStyleSourceData();
     }
@@ -95,7 +95,7 @@
 };
 
 struct CSSMediaQuerySourceData : public GarbageCollected<CSSMediaQuerySourceData> {
-    static RawPtr<CSSMediaQuerySourceData> create()
+    static CSSMediaQuerySourceData* create()
     {
         return new CSSMediaQuerySourceData();
     }
@@ -109,7 +109,7 @@
 };
 
 struct CSSMediaSourceData : public GarbageCollected<CSSMediaSourceData> {
-    static RawPtr<CSSMediaSourceData> create()
+    static CSSMediaSourceData* create()
     {
         return new CSSMediaSourceData();
     }
@@ -127,7 +127,7 @@
 using SelectorRangeList = HeapVector<SourceRange>;
 
 struct CSSRuleSourceData : public GarbageCollected<CSSRuleSourceData> {
-    static RawPtr<CSSRuleSourceData> create(StyleRule::RuleType type)
+    static CSSRuleSourceData* create(StyleRule::RuleType type)
     {
         return new CSSRuleSourceData(type);
     }
diff --git a/third_party/WebKit/Source/core/css/CSSQuadValue.h b/third_party/WebKit/Source/core/css/CSSQuadValue.h
index 7bab573..b86bd77 100644
--- a/third_party/WebKit/Source/core/css/CSSQuadValue.h
+++ b/third_party/WebKit/Source/core/css/CSSQuadValue.h
@@ -35,7 +35,7 @@
         SerializeAsQuad
     };
 
-    static RawPtr<CSSQuadValue> create(RawPtr<CSSPrimitiveValue> top, RawPtr<CSSPrimitiveValue> right, RawPtr<CSSPrimitiveValue> bottom, RawPtr<CSSPrimitiveValue> left, TypeForSerialization serializationType)
+    static CSSQuadValue* create(CSSPrimitiveValue* top, CSSPrimitiveValue* right, CSSPrimitiveValue* bottom, CSSPrimitiveValue* left, TypeForSerialization serializationType)
     {
         return new CSSQuadValue(top, right, bottom, left, serializationType);
     }
@@ -60,7 +60,7 @@
     DECLARE_TRACE_AFTER_DISPATCH();
 
 protected:
-    CSSQuadValue(RawPtr<CSSPrimitiveValue> top, RawPtr<CSSPrimitiveValue> right, RawPtr<CSSPrimitiveValue> bottom, RawPtr<CSSPrimitiveValue> left, TypeForSerialization serializationType)
+    CSSQuadValue(CSSPrimitiveValue* top, CSSPrimitiveValue* right, CSSPrimitiveValue* bottom, CSSPrimitiveValue* left, TypeForSerialization serializationType)
         : CSSValue(QuadClass)
         , m_serializationType(serializationType)
         , m_top(top)
diff --git a/third_party/WebKit/Source/core/css/CSSReflectValue.h b/third_party/WebKit/Source/core/css/CSSReflectValue.h
index ac7cb34d..c7eb172 100644
--- a/third_party/WebKit/Source/core/css/CSSReflectValue.h
+++ b/third_party/WebKit/Source/core/css/CSSReflectValue.h
@@ -36,8 +36,8 @@
 
 class CSSReflectValue : public CSSValue {
 public:
-    static RawPtr<CSSReflectValue> create(RawPtr<CSSPrimitiveValue> direction,
-        RawPtr<CSSPrimitiveValue> offset, RawPtr<CSSValue> mask)
+    static CSSReflectValue* create(CSSPrimitiveValue* direction,
+        CSSPrimitiveValue* offset, CSSValue* mask)
     {
         return new CSSReflectValue(direction, offset, mask);
     }
@@ -53,7 +53,7 @@
     DECLARE_TRACE_AFTER_DISPATCH();
 
 private:
-    CSSReflectValue(RawPtr<CSSPrimitiveValue> direction, RawPtr<CSSPrimitiveValue> offset, RawPtr<CSSValue> mask)
+    CSSReflectValue(CSSPrimitiveValue* direction, CSSPrimitiveValue* offset, CSSValue* mask)
         : CSSValue(ReflectClass)
         , m_direction(direction)
         , m_offset(offset)
diff --git a/third_party/WebKit/Source/core/css/CSSRuleList.h b/third_party/WebKit/Source/core/css/CSSRuleList.h
index 50e54660..e22ee18ac 100644
--- a/third_party/WebKit/Source/core/css/CSSRuleList.h
+++ b/third_party/WebKit/Source/core/css/CSSRuleList.h
@@ -57,7 +57,7 @@
 
 class StaticCSSRuleList final : public CSSRuleList {
 public:
-    static RawPtr<StaticCSSRuleList> create()
+    static StaticCSSRuleList* create()
     {
         return new StaticCSSRuleList();
     }
@@ -89,7 +89,7 @@
 template <class Rule>
 class LiveCSSRuleList final : public CSSRuleList {
 public:
-    static RawPtr<LiveCSSRuleList> create(Rule* rule)
+    static LiveCSSRuleList* create(Rule* rule)
     {
         return new LiveCSSRuleList(rule);
     }
diff --git a/third_party/WebKit/Source/core/css/CSSSVGDocumentValue.h b/third_party/WebKit/Source/core/css/CSSSVGDocumentValue.h
index c53abee..fea4004b 100644
--- a/third_party/WebKit/Source/core/css/CSSSVGDocumentValue.h
+++ b/third_party/WebKit/Source/core/css/CSSSVGDocumentValue.h
@@ -34,7 +34,7 @@
 
 class CSSSVGDocumentValue : public CSSValue {
 public:
-    static RawPtr<CSSSVGDocumentValue> create(const String& url)
+    static CSSSVGDocumentValue* create(const String& url)
     {
         return new CSSSVGDocumentValue(url);
     }
diff --git a/third_party/WebKit/Source/core/css/CSSSegmentedFontFace.cpp b/third_party/WebKit/Source/core/css/CSSSegmentedFontFace.cpp
index 4226d1c2..f563903 100644
--- a/third_party/WebKit/Source/core/css/CSSSegmentedFontFace.cpp
+++ b/third_party/WebKit/Source/core/css/CSSSegmentedFontFace.cpp
@@ -76,9 +76,8 @@
     pruneTable();
 }
 
-void CSSSegmentedFontFace::addFontFace(RawPtr<FontFace> prpFontFace, bool cssConnected)
+void CSSSegmentedFontFace::addFontFace(FontFace* fontFace, bool cssConnected)
 {
-    RawPtr<FontFace> fontFace = prpFontFace;
     pruneTable();
     fontFace->cssFontFace()->setSegmentedFontFace(this);
     if (cssConnected) {
@@ -91,9 +90,8 @@
     }
 }
 
-void CSSSegmentedFontFace::removeFontFace(RawPtr<FontFace> prpFontFace)
+void CSSSegmentedFontFace::removeFontFace(FontFace* fontFace)
 {
-    RawPtr<FontFace> fontFace = prpFontFace;
     FontFaceList::iterator it = m_fontFaces.find(fontFace);
     if (it == m_fontFaces.end())
         return;
diff --git a/third_party/WebKit/Source/core/css/CSSSegmentedFontFace.h b/third_party/WebKit/Source/core/css/CSSSegmentedFontFace.h
index 8c9cd9b8..b2346f252 100644
--- a/third_party/WebKit/Source/core/css/CSSSegmentedFontFace.h
+++ b/third_party/WebKit/Source/core/css/CSSSegmentedFontFace.h
@@ -47,7 +47,7 @@
 
 class CSSSegmentedFontFace final : public GarbageCollectedFinalized<CSSSegmentedFontFace> {
 public:
-    static RawPtr<CSSSegmentedFontFace> create(CSSFontSelector* selector, FontTraits traits)
+    static CSSSegmentedFontFace* create(CSSFontSelector* selector, FontTraits traits)
     {
         return new CSSSegmentedFontFace(selector, traits);
     }
@@ -60,8 +60,8 @@
     // so cached FontData must be discarded.
     void fontFaceInvalidated();
 
-    void addFontFace(RawPtr<FontFace>, bool cssConnected);
-    void removeFontFace(RawPtr<FontFace>);
+    void addFontFace(FontFace*, bool cssConnected);
+    void removeFontFace(FontFace*);
     bool isEmpty() const { return m_fontFaces.isEmpty(); }
 
     PassRefPtr<FontData> getFontData(const FontDescription&);
diff --git a/third_party/WebKit/Source/core/css/CSSShadowValue.cpp b/third_party/WebKit/Source/core/css/CSSShadowValue.cpp
index 8f727289e..987ca57 100644
--- a/third_party/WebKit/Source/core/css/CSSShadowValue.cpp
+++ b/third_party/WebKit/Source/core/css/CSSShadowValue.cpp
@@ -26,12 +26,12 @@
 namespace blink {
 
 // Used for text-shadow and box-shadow
-CSSShadowValue::CSSShadowValue(RawPtr<CSSPrimitiveValue> x,
-    RawPtr<CSSPrimitiveValue> y,
-    RawPtr<CSSPrimitiveValue> blur,
-    RawPtr<CSSPrimitiveValue> spread,
-    RawPtr<CSSPrimitiveValue> style,
-    RawPtr<CSSValue> color)
+CSSShadowValue::CSSShadowValue(CSSPrimitiveValue* x,
+    CSSPrimitiveValue* y,
+    CSSPrimitiveValue* blur,
+    CSSPrimitiveValue* spread,
+    CSSPrimitiveValue* style,
+    CSSValue* color)
     : CSSValue(ShadowClass)
     , x(x)
     , y(y)
diff --git a/third_party/WebKit/Source/core/css/CSSShadowValue.h b/third_party/WebKit/Source/core/css/CSSShadowValue.h
index 908e1633..66a6e82a 100644
--- a/third_party/WebKit/Source/core/css/CSSShadowValue.h
+++ b/third_party/WebKit/Source/core/css/CSSShadowValue.h
@@ -33,12 +33,12 @@
 // Used for text-shadow and box-shadow
 class CORE_EXPORT CSSShadowValue : public CSSValue {
 public:
-    static RawPtr<CSSShadowValue> create(RawPtr<CSSPrimitiveValue> x,
-        RawPtr<CSSPrimitiveValue> y,
-        RawPtr<CSSPrimitiveValue> blur,
-        RawPtr<CSSPrimitiveValue> spread,
-        RawPtr<CSSPrimitiveValue> style,
-        RawPtr<CSSValue> color)
+    static CSSShadowValue* create(CSSPrimitiveValue* x,
+        CSSPrimitiveValue* y,
+        CSSPrimitiveValue* blur,
+        CSSPrimitiveValue* spread,
+        CSSPrimitiveValue* style,
+        CSSValue* color)
     {
         return new CSSShadowValue(x, y, blur, spread, style, color);
     }
@@ -57,12 +57,12 @@
     DECLARE_TRACE_AFTER_DISPATCH();
 
 private:
-    CSSShadowValue(RawPtr<CSSPrimitiveValue> x,
-        RawPtr<CSSPrimitiveValue> y,
-        RawPtr<CSSPrimitiveValue> blur,
-        RawPtr<CSSPrimitiveValue> spread,
-        RawPtr<CSSPrimitiveValue> style,
-        RawPtr<CSSValue> color);
+    CSSShadowValue(CSSPrimitiveValue* x,
+        CSSPrimitiveValue* y,
+        CSSPrimitiveValue* blur,
+        CSSPrimitiveValue* spread,
+        CSSPrimitiveValue* style,
+        CSSValue* color);
 };
 
 DEFINE_CSS_VALUE_TYPE_CASTS(CSSShadowValue, isShadowValue());
diff --git a/third_party/WebKit/Source/core/css/CSSStringValue.h b/third_party/WebKit/Source/core/css/CSSStringValue.h
index 1309f7e..a6c733b7 100644
--- a/third_party/WebKit/Source/core/css/CSSStringValue.h
+++ b/third_party/WebKit/Source/core/css/CSSStringValue.h
@@ -13,7 +13,7 @@
 
 class CSSStringValue : public CSSValue {
 public:
-    static RawPtr<CSSStringValue> create(const String& str)
+    static CSSStringValue* create(const String& str)
     {
         return new CSSStringValue(str);
     }
diff --git a/third_party/WebKit/Source/core/css/CSSStyleDeclaration.h b/third_party/WebKit/Source/core/css/CSSStyleDeclaration.h
index 3e0ba1c..64703eef 100644
--- a/third_party/WebKit/Source/core/css/CSSStyleDeclaration.h
+++ b/third_party/WebKit/Source/core/css/CSSStyleDeclaration.h
@@ -69,7 +69,7 @@
     // CSSPropertyID versions of the CSSOM functions to support bindings and editing.
     // Use the non-virtual methods in the concrete subclasses when possible.
     // The CSSValue returned by this function should not be exposed to the web as it may be used by multiple documents at the same time.
-    virtual RawPtr<CSSValue> getPropertyCSSValueInternal(CSSPropertyID) = 0;
+    virtual CSSValue* getPropertyCSSValueInternal(CSSPropertyID) = 0;
     virtual String getPropertyValueInternal(CSSPropertyID) = 0;
     virtual void setPropertyInternal(CSSPropertyID, const String& propertyValue, const String& value, bool important, ExceptionState&) = 0;
 
diff --git a/third_party/WebKit/Source/core/css/CSSStyleRule.h b/third_party/WebKit/Source/core/css/CSSStyleRule.h
index 66a6253..9282a6d 100644
--- a/third_party/WebKit/Source/core/css/CSSStyleRule.h
+++ b/third_party/WebKit/Source/core/css/CSSStyleRule.h
@@ -34,7 +34,7 @@
 class CORE_EXPORT CSSStyleRule final : public CSSRule {
     DEFINE_WRAPPERTYPEINFO();
 public:
-    static RawPtr<CSSStyleRule> create(StyleRule* rule, CSSStyleSheet* sheet)
+    static CSSStyleRule* create(StyleRule* rule, CSSStyleSheet* sheet)
     {
         return new CSSStyleRule(rule, sheet);
     }
diff --git a/third_party/WebKit/Source/core/css/CSSStyleSheet.cpp b/third_party/WebKit/Source/core/css/CSSStyleSheet.cpp
index 8da1f377..a811fe1e 100644
--- a/third_party/WebKit/Source/core/css/CSSStyleSheet.cpp
+++ b/third_party/WebKit/Source/core/css/CSSStyleSheet.cpp
@@ -46,7 +46,7 @@
 
 class StyleSheetCSSRuleList final : public CSSRuleList {
 public:
-    static RawPtr<StyleSheetCSSRuleList> create(CSSStyleSheet* sheet)
+    static StyleSheetCSSRuleList* create(CSSStyleSheet* sheet)
     {
         return new StyleSheetCSSRuleList(sheet);
     }
@@ -90,30 +90,30 @@
 }
 #endif
 
-RawPtr<CSSStyleSheet> CSSStyleSheet::create(RawPtr<StyleSheetContents> sheet, CSSImportRule* ownerRule)
+CSSStyleSheet* CSSStyleSheet::create(StyleSheetContents* sheet, CSSImportRule* ownerRule)
 {
     return new CSSStyleSheet(sheet, ownerRule);
 }
 
-RawPtr<CSSStyleSheet> CSSStyleSheet::create(RawPtr<StyleSheetContents> sheet, Node* ownerNode)
+CSSStyleSheet* CSSStyleSheet::create(StyleSheetContents* sheet, Node* ownerNode)
 {
     return new CSSStyleSheet(sheet, ownerNode, false, TextPosition::minimumPosition());
 }
 
-RawPtr<CSSStyleSheet> CSSStyleSheet::createInline(RawPtr<StyleSheetContents> sheet, Node* ownerNode, const TextPosition& startPosition)
+CSSStyleSheet* CSSStyleSheet::createInline(StyleSheetContents* sheet, Node* ownerNode, const TextPosition& startPosition)
 {
     ASSERT(sheet);
     return new CSSStyleSheet(sheet, ownerNode, true, startPosition);
 }
 
-RawPtr<CSSStyleSheet> CSSStyleSheet::createInline(Node* ownerNode, const KURL& baseURL, const TextPosition& startPosition, const String& encoding)
+CSSStyleSheet* CSSStyleSheet::createInline(Node* ownerNode, const KURL& baseURL, const TextPosition& startPosition, const String& encoding)
 {
     CSSParserContext parserContext(ownerNode->document(), 0, baseURL, encoding);
-    RawPtr<StyleSheetContents> sheet = StyleSheetContents::create(baseURL.getString(), parserContext);
-    return new CSSStyleSheet(sheet.release(), ownerNode, true, startPosition);
+    StyleSheetContents* sheet = StyleSheetContents::create(baseURL.getString(), parserContext);
+    return new CSSStyleSheet(sheet, ownerNode, true, startPosition);
 }
 
-CSSStyleSheet::CSSStyleSheet(RawPtr<StyleSheetContents> contents, CSSImportRule* ownerRule)
+CSSStyleSheet::CSSStyleSheet(StyleSheetContents* contents, CSSImportRule* ownerRule)
     : m_contents(contents)
     , m_isInlineStylesheet(false)
     , m_isDisabled(false)
@@ -125,7 +125,7 @@
     m_contents->registerClient(this);
 }
 
-CSSStyleSheet::CSSStyleSheet(RawPtr<StyleSheetContents> contents, Node* ownerNode, bool isInlineStylesheet, const TextPosition& startPosition)
+CSSStyleSheet::CSSStyleSheet(StyleSheetContents* contents, Node* ownerNode, bool isInlineStylesheet, const TextPosition& startPosition)
     : m_contents(contents)
     , m_isInlineStylesheet(isInlineStylesheet)
     , m_isDisabled(false)
@@ -222,7 +222,7 @@
     didMutate();
 }
 
-void CSSStyleSheet::setMediaQueries(RawPtr<MediaQuerySet> mediaQueries)
+void CSSStyleSheet::setMediaQueries(MediaQuerySet* mediaQueries)
 {
     m_mediaQueries = mediaQueries;
     if (m_mediaCSSOMWrapper && m_mediaQueries)
@@ -276,7 +276,7 @@
     return false;
 }
 
-RawPtr<CSSRuleList> CSSStyleSheet::rules()
+CSSRuleList* CSSStyleSheet::rules()
 {
     return cssRules();
 }
@@ -290,7 +290,7 @@
         return 0;
     }
     CSSParserContext context(m_contents->parserContext(), UseCounter::getFrom(this));
-    RawPtr<StyleRuleBase> rule = CSSParser::parseRule(context, m_contents.get(), ruleString);
+    StyleRuleBase* rule = CSSParser::parseRule(context, m_contents.get(), ruleString);
 
     if (!rule) {
         exceptionState.throwDOMException(SyntaxError, "Failed to parse the rule '" + ruleString + "'.");
@@ -362,7 +362,7 @@
 }
 
 
-RawPtr<CSSRuleList> CSSStyleSheet::cssRules()
+CSSRuleList* CSSStyleSheet::cssRules()
 {
     if (!canAccessRules())
         return nullptr;
diff --git a/third_party/WebKit/Source/core/css/CSSStyleSheet.h b/third_party/WebKit/Source/core/css/CSSStyleSheet.h
index cbe6791e..167da84e 100644
--- a/third_party/WebKit/Source/core/css/CSSStyleSheet.h
+++ b/third_party/WebKit/Source/core/css/CSSStyleSheet.h
@@ -48,10 +48,10 @@
 class CORE_EXPORT CSSStyleSheet final : public StyleSheet {
     DEFINE_WRAPPERTYPEINFO();
 public:
-    static RawPtr<CSSStyleSheet> create(RawPtr<StyleSheetContents>, CSSImportRule* ownerRule = 0);
-    static RawPtr<CSSStyleSheet> create(RawPtr<StyleSheetContents>, Node* ownerNode);
-    static RawPtr<CSSStyleSheet> createInline(Node*, const KURL&, const TextPosition& startPosition = TextPosition::minimumPosition(), const String& encoding = String());
-    static RawPtr<CSSStyleSheet> createInline(RawPtr<StyleSheetContents>, Node* ownerNode, const TextPosition& startPosition = TextPosition::minimumPosition());
+    static CSSStyleSheet* create(StyleSheetContents*, CSSImportRule* ownerRule = 0);
+    static CSSStyleSheet* create(StyleSheetContents*, Node* ownerNode);
+    static CSSStyleSheet* createInline(Node*, const KURL&, const TextPosition& startPosition = TextPosition::minimumPosition(), const String& encoding = String());
+    static CSSStyleSheet* createInline(StyleSheetContents*, Node* ownerNode, const TextPosition& startPosition = TextPosition::minimumPosition());
 
     ~CSSStyleSheet() override;
 
@@ -63,13 +63,13 @@
     bool disabled() const override { return m_isDisabled; }
     void setDisabled(bool) override;
 
-    RawPtr<CSSRuleList> cssRules();
+    CSSRuleList* cssRules();
     unsigned insertRule(const String& rule, unsigned index, ExceptionState&);
     unsigned insertRule(const String& rule, ExceptionState&); // Deprecated.
     void deleteRule(unsigned index, ExceptionState&);
 
     // IE Extensions
-    RawPtr<CSSRuleList> rules();
+    CSSRuleList* rules();
     int addRule(const String& selector, const String& style, int index, ExceptionState&);
     int addRule(const String& selector, const String& style, ExceptionState&);
     void removeRule(unsigned index, ExceptionState& exceptionState) { deleteRule(index, exceptionState); }
@@ -87,7 +87,7 @@
     void clearOwnerRule() { m_ownerRule = nullptr; }
     Document* ownerDocument() const;
     MediaQuerySet* mediaQueries() const { return m_mediaQueries.get(); }
-    void setMediaQueries(RawPtr<MediaQuerySet>);
+    void setMediaQueries(MediaQuerySet*);
     void setTitle(const String& title) { m_title = title; }
     // Set by LinkStyle iff CORS-enabled fetch of stylesheet succeeded from this origin.
     void setAllowRuleAccessFromOrigin(PassRefPtr<SecurityOrigin> allowedOrigin);
@@ -121,8 +121,8 @@
     DECLARE_VIRTUAL_TRACE();
 
 private:
-    CSSStyleSheet(RawPtr<StyleSheetContents>, CSSImportRule* ownerRule);
-    CSSStyleSheet(RawPtr<StyleSheetContents>, Node* ownerNode, bool isInlineStylesheet, const TextPosition& startPosition);
+    CSSStyleSheet(StyleSheetContents*, CSSImportRule* ownerRule);
+    CSSStyleSheet(StyleSheetContents*, Node* ownerNode, bool isInlineStylesheet, const TextPosition& startPosition);
 
     bool isCSSStyleSheet() const override { return true; }
     String type() const override { return "text/css"; }
diff --git a/third_party/WebKit/Source/core/css/CSSStyleSheetResourceTest.cpp b/third_party/WebKit/Source/core/css/CSSStyleSheetResourceTest.cpp
index 778198d..38deac0 100644
--- a/third_party/WebKit/Source/core/css/CSSStyleSheetResourceTest.cpp
+++ b/third_party/WebKit/Source/core/css/CSSStyleSheetResourceTest.cpp
@@ -70,15 +70,15 @@
         // the image resource.
         document()->fetcher()->setAutoLoadImages(false);
 
-        RawPtr<CSSStyleSheetResource> cssResource = CSSStyleSheetResource::createForTest(ResourceRequest(cssURL), "utf-8");
-        memoryCache()->add(cssResource.get());
+        CSSStyleSheetResource* cssResource = CSSStyleSheetResource::createForTest(ResourceRequest(cssURL), "utf-8");
+        memoryCache()->add(cssResource);
         cssResource->responseReceived(ResourceResponse(cssURL, "style/css", 0, nullAtom, String()), nullptr);
         cssResource->finish();
 
-        RawPtr<StyleSheetContents> contents = StyleSheetContents::create(CSSParserContext(HTMLStandardMode, nullptr));
-        RawPtr<CSSStyleSheet> sheet = CSSStyleSheet::create(contents, document());
+        StyleSheetContents* contents = StyleSheetContents::create(CSSParserContext(HTMLStandardMode, nullptr));
+        CSSStyleSheet* sheet = CSSStyleSheet::create(contents, document());
         EXPECT_TRUE(sheet);
-        RawPtr<CSSCrossfadeValue> crossfade = CSSCrossfadeValue::create(
+        CSSCrossfadeValue* crossfade = CSSCrossfadeValue::create(
             CSSImageValue::create(String("image"), imageURL),
             CSSImageValue::create(String("image"), imageURL),
             CSSPrimitiveValue::create(1.0, CSSPrimitiveValue::UnitType::Number));
@@ -91,7 +91,7 @@
             StyleRule::create(CSSSelectorList::adoptSelectorVector(selectors), ImmutableStylePropertySet::create(&property, 1, HTMLStandardMode)));
 
         crossfade->loadSubimages(document());
-        RawPtr<Resource> imageResource = memoryCache()->resourceForURL(imageURL, MemoryCache::defaultCacheIdentifier());
+        Resource* imageResource = memoryCache()->resourceForURL(imageURL, MemoryCache::defaultCacheIdentifier());
         ASSERT_TRUE(imageResource);
         ResourceResponse imageResponse;
         imageResponse.setURL(imageURL);
@@ -101,16 +101,16 @@
         contents->checkLoaded();
         cssResource->saveParsedStyleSheet(contents);
 
-        memoryCache()->update(cssResource.get(), cssResource->size(), cssResource->size(), false);
-        memoryCache()->update(imageResource.get(), imageResource->size(), imageResource->size(), false);
-        if (!memoryCache()->isInSameLRUListForTest(cssResource.get(), imageResource.get())) {
+        memoryCache()->update(cssResource, cssResource->size(), cssResource->size(), false);
+        memoryCache()->update(imageResource, imageResource->size(), imageResource->size(), false);
+        if (!memoryCache()->isInSameLRUListForTest(cssResource, imageResource)) {
             // We assume that the LRU list is determined by |size / accessCount|.
             for (size_t i = 0; i < cssResource->size() + 1; ++i)
-                memoryCache()->update(cssResource.get(), cssResource->size(), cssResource->size(), true);
+                memoryCache()->update(cssResource, cssResource->size(), cssResource->size(), true);
             for (size_t i = 0; i < imageResource->size() + 1; ++i)
-                memoryCache()->update(imageResource.get(), imageResource->size(), imageResource->size(), true);
+                memoryCache()->update(imageResource, imageResource->size(), imageResource->size(), true);
         }
-        ASSERT_TRUE(memoryCache()->isInSameLRUListForTest(cssResource.get(), imageResource.get()));
+        ASSERT_TRUE(memoryCache()->isInSameLRUListForTest(cssResource, imageResource));
     }
     Heap::collectAllGarbage();
     // This operation should not lead to crash!
@@ -125,17 +125,17 @@
 
     // Emulate using <img> to do async stylesheet preloads.
 
-    RawPtr<Resource> imageResource = ImageResource::create(ResourceRequest(imageURL), nullptr);
+    Resource* imageResource = ImageResource::create(ResourceRequest(imageURL), nullptr);
     ASSERT_TRUE(imageResource);
-    memoryCache()->add(imageResource.get());
-    ASSERT_TRUE(memoryCache()->contains(imageResource.get()));
+    memoryCache()->add(imageResource);
+    ASSERT_TRUE(memoryCache()->contains(imageResource));
 
-    RawPtr<CSSStyleSheetResource> cssResource = CSSStyleSheetResource::createForTest(ResourceRequest(cssURL), "utf-8");
+    CSSStyleSheetResource* cssResource = CSSStyleSheetResource::createForTest(ResourceRequest(cssURL), "utf-8");
     cssResource->responseReceived(ResourceResponse(cssURL, "style/css", 0, nullAtom, String()), nullptr);
     cssResource->finish();
 
-    RawPtr<StyleSheetContents> contents = StyleSheetContents::create(CSSParserContext(HTMLStandardMode, nullptr));
-    RawPtr<CSSStyleSheet> sheet = CSSStyleSheet::create(contents, document());
+    StyleSheetContents* contents = StyleSheetContents::create(CSSParserContext(HTMLStandardMode, nullptr));
+    CSSStyleSheet* sheet = CSSStyleSheet::create(contents, document());
     EXPECT_TRUE(sheet);
 
     contents->checkLoaded();
@@ -144,8 +144,8 @@
     // Verify that the cache will have a mapping for |imageResource| at |url|.
     // The underlying |contents| for the stylesheet resource must have a
     // matching cache status.
-    ASSERT_TRUE(memoryCache()->contains(imageResource.get()));
-    ASSERT_FALSE(memoryCache()->contains(cssResource.get()));
+    ASSERT_TRUE(memoryCache()->contains(imageResource));
+    ASSERT_FALSE(memoryCache()->contains(cssResource));
     ASSERT_FALSE(contents->isInMemoryCache());
 }
 
diff --git a/third_party/WebKit/Source/core/css/CSSSupportsRule.h b/third_party/WebKit/Source/core/css/CSSSupportsRule.h
index b2a89d7..fd3b3a4 100644
--- a/third_party/WebKit/Source/core/css/CSSSupportsRule.h
+++ b/third_party/WebKit/Source/core/css/CSSSupportsRule.h
@@ -38,7 +38,7 @@
 class CSSSupportsRule final : public CSSGroupingRule {
     DEFINE_WRAPPERTYPEINFO();
 public:
-    static RawPtr<CSSSupportsRule> create(StyleRuleSupports* rule, CSSStyleSheet* sheet)
+    static CSSSupportsRule* create(StyleRuleSupports* rule, CSSStyleSheet* sheet)
     {
         return new CSSSupportsRule(rule, sheet);
     }
diff --git a/third_party/WebKit/Source/core/css/CSSTestHelper.cpp b/third_party/WebKit/Source/core/css/CSSTestHelper.cpp
index ab513d8..8a18210 100644
--- a/third_party/WebKit/Source/core/css/CSSTestHelper.cpp
+++ b/third_party/WebKit/Source/core/css/CSSTestHelper.cpp
@@ -52,7 +52,7 @@
 
 CSSRuleList* CSSTestHelper::cssRules()
 {
-    return m_styleSheet->cssRules().get();
+    return m_styleSheet->cssRules();
 }
 
 RuleSet& CSSTestHelper::ruleSet()
diff --git a/third_party/WebKit/Source/core/css/CSSTimingFunctionValue.h b/third_party/WebKit/Source/core/css/CSSTimingFunctionValue.h
index f2d159a..4115442 100644
--- a/third_party/WebKit/Source/core/css/CSSTimingFunctionValue.h
+++ b/third_party/WebKit/Source/core/css/CSSTimingFunctionValue.h
@@ -34,7 +34,7 @@
 
 class CSSCubicBezierTimingFunctionValue : public CSSValue {
 public:
-    static RawPtr<CSSCubicBezierTimingFunctionValue> create(double x1, double y1, double x2, double y2)
+    static CSSCubicBezierTimingFunctionValue* create(double x1, double y1, double x2, double y2)
     {
         return new CSSCubicBezierTimingFunctionValue(x1, y1, x2, y2);
     }
@@ -70,7 +70,7 @@
 
 class CSSStepsTimingFunctionValue : public CSSValue {
 public:
-    static RawPtr<CSSStepsTimingFunctionValue> create(int steps, StepsTimingFunction::StepAtPosition stepAtPosition)
+    static CSSStepsTimingFunctionValue* create(int steps, StepsTimingFunction::StepAtPosition stepAtPosition)
     {
         return new CSSStepsTimingFunctionValue(steps, stepAtPosition);
     }
diff --git a/third_party/WebKit/Source/core/css/CSSURIValue.h b/third_party/WebKit/Source/core/css/CSSURIValue.h
index f773787..a36de15 100644
--- a/third_party/WebKit/Source/core/css/CSSURIValue.h
+++ b/third_party/WebKit/Source/core/css/CSSURIValue.h
@@ -13,7 +13,7 @@
 
 class CSSURIValue : public CSSValue {
 public:
-    static RawPtr<CSSURIValue> create(const String& str)
+    static CSSURIValue* create(const String& str)
     {
         return new CSSURIValue(str);
     }
diff --git a/third_party/WebKit/Source/core/css/CSSUnicodeRangeValue.h b/third_party/WebKit/Source/core/css/CSSUnicodeRangeValue.h
index 10a783d..cf77633 100644
--- a/third_party/WebKit/Source/core/css/CSSUnicodeRangeValue.h
+++ b/third_party/WebKit/Source/core/css/CSSUnicodeRangeValue.h
@@ -33,7 +33,7 @@
 
 class CSSUnicodeRangeValue : public CSSValue {
 public:
-    static RawPtr<CSSUnicodeRangeValue> create(UChar32 from, UChar32 to)
+    static CSSUnicodeRangeValue* create(UChar32 from, UChar32 to)
     {
         return new CSSUnicodeRangeValue(from, to);
     }
diff --git a/third_party/WebKit/Source/core/css/CSSUnsetValue.h b/third_party/WebKit/Source/core/css/CSSUnsetValue.h
index 3d36ddb..ff12e75 100644
--- a/third_party/WebKit/Source/core/css/CSSUnsetValue.h
+++ b/third_party/WebKit/Source/core/css/CSSUnsetValue.h
@@ -12,7 +12,7 @@
 
 class CSSUnsetValue : public CSSValue {
 public:
-    static RawPtr<CSSUnsetValue> create()
+    static CSSUnsetValue* create()
     {
         return new CSSUnsetValue;
     }
diff --git a/third_party/WebKit/Source/core/css/CSSValue.h b/third_party/WebKit/Source/core/css/CSSValue.h
index d8c14eb..9547537 100644
--- a/third_party/WebKit/Source/core/css/CSSValue.h
+++ b/third_party/WebKit/Source/core/css/CSSValue.h
@@ -256,7 +256,7 @@
 }
 
 template<typename CSSValueType>
-inline bool compareCSSValuePtr(const RawPtr<CSSValueType>& first, const RawPtr<CSSValueType>& second)
+inline bool compareCSSValuePtr(const CSSValueType* first, const CSSValueType* second)
 {
     if (first == second)
         return true;
diff --git a/third_party/WebKit/Source/core/css/CSSValueList.cpp b/third_party/WebKit/Source/core/css/CSSValueList.cpp
index b83cfa2..d00d050 100644
--- a/third_party/WebKit/Source/core/css/CSSValueList.cpp
+++ b/third_party/WebKit/Source/core/css/CSSValueList.cpp
@@ -61,9 +61,9 @@
     return false;
 }
 
-RawPtr<CSSValueList> CSSValueList::copy()
+CSSValueList* CSSValueList::copy()
 {
-    RawPtr<CSSValueList> newList = nullptr;
+    CSSValueList* newList = nullptr;
     switch (m_valueListSeparator) {
     case SpaceSeparator:
         newList = createSpaceSeparated();
@@ -79,7 +79,7 @@
     }
     for (size_t index = 0; index < m_values.size(); index++)
         newList->append(m_values[index]);
-    return newList.release();
+    return newList;
 }
 
 String CSSValueList::customCSSText() const
diff --git a/third_party/WebKit/Source/core/css/CSSValueList.h b/third_party/WebKit/Source/core/css/CSSValueList.h
index 2a88943..66c3e97 100644
--- a/third_party/WebKit/Source/core/css/CSSValueList.h
+++ b/third_party/WebKit/Source/core/css/CSSValueList.h
@@ -33,15 +33,15 @@
     using iterator = HeapVector<Member<CSSValue>, 4>::iterator;
     using const_iterator = HeapVector<Member<CSSValue>, 4>::const_iterator;
 
-    static RawPtr<CSSValueList> createCommaSeparated()
+    static CSSValueList* createCommaSeparated()
     {
         return new CSSValueList(CommaSeparator);
     }
-    static RawPtr<CSSValueList> createSpaceSeparated()
+    static CSSValueList* createSpaceSeparated()
     {
         return new CSSValueList(SpaceSeparator);
     }
-    static RawPtr<CSSValueList> createSlashSeparated()
+    static CSSValueList* createSlashSeparated()
     {
         return new CSSValueList(SlashSeparator);
     }
@@ -57,11 +57,11 @@
     CSSValue* itemWithBoundsCheck(size_t index) { return index < m_values.size() ? m_values[index].get() : nullptr; }
     const CSSValue* itemWithBoundsCheck(size_t index) const { return index < m_values.size() ? m_values[index].get() : nullptr; }
 
-    void append(RawPtr<CSSValue> value) { m_values.append(value); }
-    void prepend(RawPtr<CSSValue> value) { m_values.prepend(value); }
+    void append(CSSValue* value) { m_values.append(value); }
+    void prepend(CSSValue* value) { m_values.prepend(value); }
     bool removeAll(CSSValue*);
     bool hasValue(CSSValue*) const;
-    RawPtr<CSSValueList> copy();
+    CSSValueList* copy();
 
     String customCSSText() const;
     bool equals(const CSSValueList&) const;
diff --git a/third_party/WebKit/Source/core/css/CSSValuePair.h b/third_party/WebKit/Source/core/css/CSSValuePair.h
index d9a5634..11eb744 100644
--- a/third_party/WebKit/Source/core/css/CSSValuePair.h
+++ b/third_party/WebKit/Source/core/css/CSSValuePair.h
@@ -36,13 +36,13 @@
 public:
     enum IdenticalValuesPolicy { DropIdenticalValues, KeepIdenticalValues };
 
-    static RawPtr<CSSValuePair> create(RawPtr<CSSValue> first, RawPtr<CSSValue> second,
+    static CSSValuePair* create(CSSValue* first, CSSValue* second,
         IdenticalValuesPolicy identicalValuesPolicy)
     {
         return new CSSValuePair(first, second, identicalValuesPolicy);
     }
 
-    static RawPtr<CSSValuePair> create(const LengthSize& lengthSize, const ComputedStyle& style)
+    static CSSValuePair* create(const LengthSize& lengthSize, const ComputedStyle& style)
     {
         return new CSSValuePair(CSSPrimitiveValue::create(lengthSize.width(), style.effectiveZoom()), CSSPrimitiveValue::create(lengthSize.height(), style.effectiveZoom()), KeepIdenticalValues);
     }
@@ -72,7 +72,7 @@
     DECLARE_TRACE_AFTER_DISPATCH();
 
 private:
-    CSSValuePair(RawPtr<CSSValue> first, RawPtr<CSSValue> second, IdenticalValuesPolicy identicalValuesPolicy)
+    CSSValuePair(CSSValue* first, CSSValue* second, IdenticalValuesPolicy identicalValuesPolicy)
         : CSSValue(ValuePairClass)
         , m_first(first)
         , m_second(second)
diff --git a/third_party/WebKit/Source/core/css/CSSValuePool.cpp b/third_party/WebKit/Source/core/css/CSSValuePool.cpp
index 12c18bc..58102f2c 100644
--- a/third_party/WebKit/Source/core/css/CSSValuePool.cpp
+++ b/third_party/WebKit/Source/core/css/CSSValuePool.cpp
@@ -53,7 +53,7 @@
     m_numberValueCache.resize(maximumCacheableIntegerValue + 1);
 }
 
-RawPtr<CSSPrimitiveValue> CSSValuePool::createIdentifierValue(CSSValueID ident)
+CSSPrimitiveValue* CSSValuePool::createIdentifierValue(CSSValueID ident)
 {
     if (ident <= 0)
         return CSSPrimitiveValue::createIdentifier(ident);
@@ -63,12 +63,12 @@
     return m_identifierValueCache[ident];
 }
 
-RawPtr<CSSCustomIdentValue> CSSValuePool::createIdentifierValue(CSSPropertyID ident)
+CSSCustomIdentValue* CSSValuePool::createIdentifierValue(CSSPropertyID ident)
 {
     return CSSCustomIdentValue::create(ident);
 }
 
-RawPtr<CSSColorValue> CSSValuePool::createColorValue(RGBA32 rgbValue)
+CSSColorValue* CSSValuePool::createColorValue(RGBA32 rgbValue)
 {
     // These are the empty and deleted values of the hash table.
     if (rgbValue == Color::transparent)
@@ -92,7 +92,7 @@
     if (m_colorValueCache.size() > maximumColorCacheSize)
         m_colorValueCache.clear();
 
-    RawPtr<CSSColorValue> dummyValue = nullptr;
+    CSSColorValue* dummyValue = nullptr;
     ColorValueCache::AddResult entry = m_colorValueCache.add(rgbValue, dummyValue);
     if (entry.isNewEntry)
         entry.storedValue->value = CSSColorValue::create(rgbValue);
@@ -100,7 +100,7 @@
     return entry.storedValue->value;
 }
 
-RawPtr<CSSPrimitiveValue> CSSValuePool::createValue(double value, CSSPrimitiveValue::UnitType type)
+CSSPrimitiveValue* CSSValuePool::createValue(double value, CSSPrimitiveValue::UnitType type)
 {
     if (std::isinf(value))
         value = 0;
@@ -131,12 +131,12 @@
     }
 }
 
-RawPtr<CSSPrimitiveValue> CSSValuePool::createValue(const Length& value, const ComputedStyle& style)
+CSSPrimitiveValue* CSSValuePool::createValue(const Length& value, const ComputedStyle& style)
 {
     return CSSPrimitiveValue::create(value, style.effectiveZoom());
 }
 
-RawPtr<CSSFontFamilyValue> CSSValuePool::createFontFamilyValue(const String& familyName)
+CSSFontFamilyValue* CSSValuePool::createFontFamilyValue(const String& familyName)
 {
     if (familyName.isNull())
         return CSSFontFamilyValue::create(familyName);
@@ -146,7 +146,7 @@
     return value;
 }
 
-RawPtr<CSSValueList> CSSValuePool::createFontFaceValue(const AtomicString& string)
+CSSValueList* CSSValuePool::createFontFaceValue(const AtomicString& string)
 {
     // Just wipe out the cache and start rebuilding if it gets too big.
     const unsigned maximumFontFaceCacheSize = 128;
@@ -155,9 +155,9 @@
 
     Member<CSSValueList>& value = m_fontFaceValueCache.add(string, nullptr).storedValue->value;
     if (!value) {
-        RawPtr<CSSValue> parsedValue = CSSParser::parseSingleValue(CSSPropertyFontFamily, string);
+        CSSValue* parsedValue = CSSParser::parseSingleValue(CSSPropertyFontFamily, string);
         if (parsedValue && parsedValue->isValueList())
-            value = toCSSValueList(parsedValue.get());
+            value = toCSSValueList(parsedValue);
     }
     return value;
 }
diff --git a/third_party/WebKit/Source/core/css/CSSValuePool.h b/third_party/WebKit/Source/core/css/CSSValuePool.h
index 7d40d63..9490f197 100644
--- a/third_party/WebKit/Source/core/css/CSSValuePool.h
+++ b/third_party/WebKit/Source/core/css/CSSValuePool.h
@@ -45,19 +45,19 @@
 
 class CORE_EXPORT CSSValuePool :  public GarbageCollectedFinalized<CSSValuePool> {
 public:
-    RawPtr<CSSValueList> createFontFaceValue(const AtomicString&);
-    RawPtr<CSSFontFamilyValue> createFontFamilyValue(const String&);
-    RawPtr<CSSInheritedValue> createInheritedValue() { return m_inheritedValue; }
-    RawPtr<CSSInitialValue> createImplicitInitialValue() { return m_implicitInitialValue; }
-    RawPtr<CSSInitialValue> createExplicitInitialValue() { return m_explicitInitialValue; }
-    RawPtr<CSSUnsetValue> createUnsetValue() { return m_unsetValue; }
-    RawPtr<CSSPrimitiveValue> createIdentifierValue(CSSValueID identifier);
-    RawPtr<CSSCustomIdentValue> createIdentifierValue(CSSPropertyID identifier);
-    RawPtr<CSSColorValue> createColorValue(RGBA32 rgbValue);
-    RawPtr<CSSPrimitiveValue> createValue(double value, CSSPrimitiveValue::UnitType);
-    RawPtr<CSSPrimitiveValue> createValue(const Length& value, const ComputedStyle&);
-    RawPtr<CSSPrimitiveValue> createValue(const Length& value, float zoom) { return CSSPrimitiveValue::create(value, zoom); }
-    template<typename T> static RawPtr<CSSPrimitiveValue> createValue(T value) { return CSSPrimitiveValue::create(value); }
+    CSSValueList* createFontFaceValue(const AtomicString&);
+    CSSFontFamilyValue* createFontFamilyValue(const String&);
+    CSSInheritedValue* createInheritedValue() { return m_inheritedValue; }
+    CSSInitialValue* createImplicitInitialValue() { return m_implicitInitialValue; }
+    CSSInitialValue* createExplicitInitialValue() { return m_explicitInitialValue; }
+    CSSUnsetValue* createUnsetValue() { return m_unsetValue; }
+    CSSPrimitiveValue* createIdentifierValue(CSSValueID identifier);
+    CSSCustomIdentValue* createIdentifierValue(CSSPropertyID identifier);
+    CSSColorValue* createColorValue(RGBA32 rgbValue);
+    CSSPrimitiveValue* createValue(double value, CSSPrimitiveValue::UnitType);
+    CSSPrimitiveValue* createValue(const Length& value, const ComputedStyle&);
+    CSSPrimitiveValue* createValue(const Length& value, float zoom) { return CSSPrimitiveValue::create(value, zoom); }
+    template<typename T> static CSSPrimitiveValue* createValue(T value) { return CSSPrimitiveValue::create(value); }
 
     DECLARE_TRACE();
 
diff --git a/third_party/WebKit/Source/core/css/CSSVariableReferenceValue.h b/third_party/WebKit/Source/core/css/CSSVariableReferenceValue.h
index d61356a..b3506d2 100644
--- a/third_party/WebKit/Source/core/css/CSSVariableReferenceValue.h
+++ b/third_party/WebKit/Source/core/css/CSSVariableReferenceValue.h
@@ -13,7 +13,7 @@
 
 class CSSVariableReferenceValue : public CSSValue {
 public:
-    static RawPtr<CSSVariableReferenceValue> create(PassRefPtr<CSSVariableData> data)
+    static CSSVariableReferenceValue* create(PassRefPtr<CSSVariableData> data)
     {
         return new CSSVariableReferenceValue(data);
     }
diff --git a/third_party/WebKit/Source/core/css/CSSViewportRule.h b/third_party/WebKit/Source/core/css/CSSViewportRule.h
index ebb191c..f80db082 100644
--- a/third_party/WebKit/Source/core/css/CSSViewportRule.h
+++ b/third_party/WebKit/Source/core/css/CSSViewportRule.h
@@ -43,7 +43,7 @@
 class CSSViewportRule final: public CSSRule {
     DEFINE_WRAPPERTYPEINFO();
 public:
-    static RawPtr<CSSViewportRule> create(StyleRuleViewport* viewportRule, CSSStyleSheet* sheet)
+    static CSSViewportRule* create(StyleRuleViewport* viewportRule, CSSStyleSheet* sheet)
     {
         return new CSSViewportRule(viewportRule, sheet);
     }
diff --git a/third_party/WebKit/Source/core/css/ComputedStyleCSSValueMapping.cpp b/third_party/WebKit/Source/core/css/ComputedStyleCSSValueMapping.cpp
index bcb26d9..fd98dbf 100644
--- a/third_party/WebKit/Source/core/css/ComputedStyleCSSValueMapping.cpp
+++ b/third_party/WebKit/Source/core/css/ComputedStyleCSSValueMapping.cpp
@@ -65,24 +65,24 @@
     return style && style->isDisplayFlexibleOrGridBox();
 }
 
-inline static RawPtr<CSSPrimitiveValue> zoomAdjustedPixelValue(double value, const ComputedStyle& style)
+inline static CSSPrimitiveValue* zoomAdjustedPixelValue(double value, const ComputedStyle& style)
 {
     return cssValuePool().createValue(adjustFloatForAbsoluteZoom(value, style), CSSPrimitiveValue::UnitType::Pixels);
 }
 
-inline static RawPtr<CSSPrimitiveValue> zoomAdjustedNumberValue(double value, const ComputedStyle& style)
+inline static CSSPrimitiveValue* zoomAdjustedNumberValue(double value, const ComputedStyle& style)
 {
     return cssValuePool().createValue(value / style.effectiveZoom(), CSSPrimitiveValue::UnitType::Number);
 }
 
-static RawPtr<CSSPrimitiveValue> zoomAdjustedPixelValueForLength(const Length& length, const ComputedStyle& style)
+static CSSPrimitiveValue* zoomAdjustedPixelValueForLength(const Length& length, const ComputedStyle& style)
 {
     if (length.isFixed())
         return zoomAdjustedPixelValue(length.value(), style);
     return cssValuePool().createValue(length, style);
 }
 
-static RawPtr<CSSPrimitiveValue> pixelValueForUnzoomedLength(const UnzoomedLength& unzoomedLength, const ComputedStyle& style)
+static CSSPrimitiveValue* pixelValueForUnzoomedLength(const UnzoomedLength& unzoomedLength, const ComputedStyle& style)
 {
     const Length& length = unzoomedLength.length();
     if (length.isFixed())
@@ -90,9 +90,9 @@
     return cssValuePool().createValue(length, style);
 }
 
-static RawPtr<CSSValueList> createPositionListForLayer(CSSPropertyID propertyID, const FillLayer& layer, const ComputedStyle& style)
+static CSSValueList* createPositionListForLayer(CSSPropertyID propertyID, const FillLayer& layer, const ComputedStyle& style)
 {
-    RawPtr<CSSValueList> positionList = CSSValueList::createSpaceSeparated();
+    CSSValueList* positionList = CSSValueList::createSpaceSeparated();
     if (layer.isBackgroundXOriginSet()) {
         ASSERT_UNUSED(propertyID, propertyID == CSSPropertyBackgroundPosition || propertyID == CSSPropertyWebkitMaskPosition);
         positionList->append(cssValuePool().createValue(layer.backgroundXOrigin()));
@@ -103,16 +103,16 @@
         positionList->append(cssValuePool().createValue(layer.backgroundYOrigin()));
     }
     positionList->append(zoomAdjustedPixelValueForLength(layer.yPosition(), style));
-    return positionList.release();
+    return positionList;
 }
 
-RawPtr<CSSValue> ComputedStyleCSSValueMapping::currentColorOrValidColor(const ComputedStyle& style, const StyleColor& color)
+CSSValue* ComputedStyleCSSValueMapping::currentColorOrValidColor(const ComputedStyle& style, const StyleColor& color)
 {
     // This function does NOT look at visited information, so that computed style doesn't expose that.
     return cssValuePool().createColorValue(color.resolve(style.color()).rgb());
 }
 
-static RawPtr<CSSValue> valueForFillSize(const FillSize& fillSize, const ComputedStyle& style)
+static CSSValue* valueForFillSize(const FillSize& fillSize, const ComputedStyle& style)
 {
     if (fillSize.type == Contain)
         return cssValuePool().createIdentifierValue(CSSValueContain);
@@ -123,13 +123,13 @@
     if (fillSize.size.height().isAuto())
         return zoomAdjustedPixelValueForLength(fillSize.size.width(), style);
 
-    RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    CSSValueList* list = CSSValueList::createSpaceSeparated();
     list->append(zoomAdjustedPixelValueForLength(fillSize.size.width(), style));
     list->append(zoomAdjustedPixelValueForLength(fillSize.size.height(), style));
-    return list.release();
+    return list;
 }
 
-static RawPtr<CSSValue> valueForFillRepeat(EFillRepeat xRepeat, EFillRepeat yRepeat)
+static CSSValue* valueForFillRepeat(EFillRepeat xRepeat, EFillRepeat yRepeat)
 {
     // For backwards compatibility, if both values are equal, just return one of them. And
     // if the two values are equivalent to repeat-x or repeat-y, just return the shorthand.
@@ -140,13 +140,13 @@
     if (xRepeat == NoRepeatFill && yRepeat == RepeatFill)
         return cssValuePool().createIdentifierValue(CSSValueRepeatY);
 
-    RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    CSSValueList* list = CSSValueList::createSpaceSeparated();
     list->append(cssValuePool().createValue(xRepeat));
     list->append(cssValuePool().createValue(yRepeat));
-    return list.release();
+    return list;
 }
 
-static RawPtr<CSSValue> valueForFillSourceType(EMaskSourceType type)
+static CSSValue* valueForFillSourceType(EMaskSourceType type)
 {
     switch (type) {
     case MaskAlpha:
@@ -160,7 +160,7 @@
     return nullptr;
 }
 
-static RawPtr<CSSValue> valueForPositionOffset(const ComputedStyle& style, CSSPropertyID propertyID, const LayoutObject* layoutObject)
+static CSSValue* valueForPositionOffset(const ComputedStyle& style, CSSPropertyID propertyID, const LayoutObject* layoutObject)
 {
     Length offset, opposite;
     switch (propertyID) {
@@ -250,13 +250,13 @@
     return zoomAdjustedPixelValueForLength(offset, style);
 }
 
-static RawPtr<CSSBorderImageSliceValue> valueForNinePieceImageSlice(const NinePieceImage& image)
+static CSSBorderImageSliceValue* valueForNinePieceImageSlice(const NinePieceImage& image)
 {
     // Create the slices.
-    RawPtr<CSSPrimitiveValue> top = nullptr;
-    RawPtr<CSSPrimitiveValue> right = nullptr;
-    RawPtr<CSSPrimitiveValue> bottom = nullptr;
-    RawPtr<CSSPrimitiveValue> left = nullptr;
+    CSSPrimitiveValue* top = nullptr;
+    CSSPrimitiveValue* right = nullptr;
+    CSSPrimitiveValue* bottom = nullptr;
+    CSSPrimitiveValue* left = nullptr;
 
     // TODO(alancutter): Make this code aware of calc lengths.
     if (image.imageSlices().top().hasPercent())
@@ -295,16 +295,16 @@
         }
     }
 
-    return CSSBorderImageSliceValue::create(CSSQuadValue::create(top.release(), right.release(), bottom.release(), left.release(), CSSQuadValue::SerializeAsQuad), image.fill());
+    return CSSBorderImageSliceValue::create(CSSQuadValue::create(top, right, bottom, left, CSSQuadValue::SerializeAsQuad), image.fill());
 }
 
-static RawPtr<CSSQuadValue> valueForNinePieceImageQuad(const BorderImageLengthBox& box, const ComputedStyle& style)
+static CSSQuadValue* valueForNinePieceImageQuad(const BorderImageLengthBox& box, const ComputedStyle& style)
 {
     // Create the slices.
-    RawPtr<CSSPrimitiveValue> top = nullptr;
-    RawPtr<CSSPrimitiveValue> right = nullptr;
-    RawPtr<CSSPrimitiveValue> bottom = nullptr;
-    RawPtr<CSSPrimitiveValue> left = nullptr;
+    CSSPrimitiveValue* top = nullptr;
+    CSSPrimitiveValue* right = nullptr;
+    CSSPrimitiveValue* bottom = nullptr;
+    CSSPrimitiveValue* left = nullptr;
 
     if (box.top().isNumber())
         top = cssValuePool().createValue(box.top().number(), CSSPrimitiveValue::UnitType::Number);
@@ -341,7 +341,7 @@
         }
     }
 
-    return CSSQuadValue::create(top.release(), right.release(), bottom.release(), left.release(), CSSQuadValue::SerializeAsQuad);
+    return CSSQuadValue::create(top, right, bottom, left, CSSQuadValue::SerializeAsQuad);
 }
 
 static CSSValueID valueForRepeatRule(int rule)
@@ -358,57 +358,57 @@
     }
 }
 
-static RawPtr<CSSValue> valueForNinePieceImageRepeat(const NinePieceImage& image)
+static CSSValue* valueForNinePieceImageRepeat(const NinePieceImage& image)
 {
-    RawPtr<CSSPrimitiveValue> horizontalRepeat = nullptr;
-    RawPtr<CSSPrimitiveValue> verticalRepeat = nullptr;
+    CSSPrimitiveValue* horizontalRepeat = nullptr;
+    CSSPrimitiveValue* verticalRepeat = nullptr;
 
     horizontalRepeat = cssValuePool().createIdentifierValue(valueForRepeatRule(image.horizontalRule()));
     if (image.horizontalRule() == image.verticalRule())
         verticalRepeat = horizontalRepeat;
     else
         verticalRepeat = cssValuePool().createIdentifierValue(valueForRepeatRule(image.verticalRule()));
-    return CSSValuePair::create(horizontalRepeat.release(), verticalRepeat.release(), CSSValuePair::DropIdenticalValues);
+    return CSSValuePair::create(horizontalRepeat, verticalRepeat, CSSValuePair::DropIdenticalValues);
 }
 
-static RawPtr<CSSValue> valueForNinePieceImage(const NinePieceImage& image, const ComputedStyle& style)
+static CSSValue* valueForNinePieceImage(const NinePieceImage& image, const ComputedStyle& style)
 {
     if (!image.hasImage())
         return cssValuePool().createIdentifierValue(CSSValueNone);
 
     // Image first.
-    RawPtr<CSSValue> imageValue = nullptr;
+    CSSValue* imageValue = nullptr;
     if (image.image())
         imageValue = image.image()->computedCSSValue();
 
     // Create the image slice.
-    RawPtr<CSSBorderImageSliceValue> imageSlices = valueForNinePieceImageSlice(image);
+    CSSBorderImageSliceValue* imageSlices = valueForNinePieceImageSlice(image);
 
     // Create the border area slices.
-    RawPtr<CSSValue> borderSlices = valueForNinePieceImageQuad(image.borderSlices(), style);
+    CSSValue* borderSlices = valueForNinePieceImageQuad(image.borderSlices(), style);
 
     // Create the border outset.
-    RawPtr<CSSValue> outset = valueForNinePieceImageQuad(image.outset(), style);
+    CSSValue* outset = valueForNinePieceImageQuad(image.outset(), style);
 
     // Create the repeat rules.
-    RawPtr<CSSValue> repeat = valueForNinePieceImageRepeat(image);
+    CSSValue* repeat = valueForNinePieceImageRepeat(image);
 
-    return createBorderImageValue(imageValue.release(), imageSlices.release(), borderSlices.release(), outset.release(), repeat.release());
+    return createBorderImageValue(imageValue, imageSlices, borderSlices, outset, repeat);
 }
 
-static RawPtr<CSSValue> valueForReflection(const StyleReflection* reflection, const ComputedStyle& style)
+static CSSValue* valueForReflection(const StyleReflection* reflection, const ComputedStyle& style)
 {
     if (!reflection)
         return cssValuePool().createIdentifierValue(CSSValueNone);
 
-    RawPtr<CSSPrimitiveValue> offset = nullptr;
+    CSSPrimitiveValue* offset = nullptr;
     // TODO(alancutter): Make this work correctly for calc lengths.
     if (reflection->offset().hasPercent())
         offset = cssValuePool().createValue(reflection->offset().percent(), CSSPrimitiveValue::UnitType::Percentage);
     else
         offset = zoomAdjustedPixelValue(reflection->offset().value(), style);
 
-    RawPtr<CSSPrimitiveValue> direction = nullptr;
+    CSSPrimitiveValue* direction = nullptr;
     switch (reflection->direction()) {
     case ReflectionBelow:
         direction = cssValuePool().createIdentifierValue(CSSValueBelow);
@@ -424,7 +424,7 @@
         break;
     }
 
-    return CSSReflectValue::create(direction.release(), offset.release(), valueForNinePieceImage(reflection->mask(), style));
+    return CSSReflectValue::create(direction, offset, valueForNinePieceImage(reflection->mask(), style));
 }
 
 static ItemPosition resolveAlignmentAuto(ItemPosition position, const ComputedStyle* style)
@@ -438,49 +438,49 @@
     return isFlexOrGrid(style) ? ItemPositionStretch : ItemPositionStart;
 }
 
-static RawPtr<CSSValueList> valueForItemPositionWithOverflowAlignment(ItemPosition itemPosition, OverflowAlignment overflowAlignment, ItemPositionType positionType)
+static CSSValueList* valueForItemPositionWithOverflowAlignment(ItemPosition itemPosition, OverflowAlignment overflowAlignment, ItemPositionType positionType)
 {
-    RawPtr<CSSValueList> result = CSSValueList::createSpaceSeparated();
+    CSSValueList* result = CSSValueList::createSpaceSeparated();
     if (positionType == LegacyPosition)
         result->append(CSSPrimitiveValue::createIdentifier(CSSValueLegacy));
     result->append(CSSPrimitiveValue::create(itemPosition));
     if (itemPosition >= ItemPositionCenter && overflowAlignment != OverflowAlignmentDefault)
         result->append(CSSPrimitiveValue::create(overflowAlignment));
     ASSERT(result->length() <= 2);
-    return result.release();
+    return result;
 }
 
-static RawPtr<CSSValueList> valuesForGridShorthand(const StylePropertyShorthand& shorthand, const ComputedStyle& style, const LayoutObject* layoutObject, Node* styledNode, bool allowVisitedStyle)
+static CSSValueList* valuesForGridShorthand(const StylePropertyShorthand& shorthand, const ComputedStyle& style, const LayoutObject* layoutObject, Node* styledNode, bool allowVisitedStyle)
 {
-    RawPtr<CSSValueList> list = CSSValueList::createSlashSeparated();
+    CSSValueList* list = CSSValueList::createSlashSeparated();
     for (size_t i = 0; i < shorthand.length(); ++i) {
-        RawPtr<CSSValue> value = ComputedStyleCSSValueMapping::get(shorthand.properties()[i], style, layoutObject, styledNode, allowVisitedStyle);
-        ASSERT(value);
-        list->append(value.release());
-    }
-    return list.release();
-}
-
-static RawPtr<CSSValueList> valuesForShorthandProperty(const StylePropertyShorthand& shorthand, const ComputedStyle& style, const LayoutObject* layoutObject, Node* styledNode, bool allowVisitedStyle)
-{
-    RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
-    for (size_t i = 0; i < shorthand.length(); ++i) {
-        RawPtr<CSSValue> value = ComputedStyleCSSValueMapping::get(shorthand.properties()[i], style, layoutObject, styledNode, allowVisitedStyle);
+        CSSValue* value = ComputedStyleCSSValueMapping::get(shorthand.properties()[i], style, layoutObject, styledNode, allowVisitedStyle);
         ASSERT(value);
         list->append(value);
     }
-    return list.release();
+    return list;
 }
 
-static RawPtr<CSSValueList> valuesForBackgroundShorthand(const ComputedStyle& style, const LayoutObject* layoutObject, Node* styledNode, bool allowVisitedStyle)
+static CSSValueList* valuesForShorthandProperty(const StylePropertyShorthand& shorthand, const ComputedStyle& style, const LayoutObject* layoutObject, Node* styledNode, bool allowVisitedStyle)
 {
-    RawPtr<CSSValueList> ret = CSSValueList::createCommaSeparated();
+    CSSValueList* list = CSSValueList::createSpaceSeparated();
+    for (size_t i = 0; i < shorthand.length(); ++i) {
+        CSSValue* value = ComputedStyleCSSValueMapping::get(shorthand.properties()[i], style, layoutObject, styledNode, allowVisitedStyle);
+        ASSERT(value);
+        list->append(value);
+    }
+    return list;
+}
+
+static CSSValueList* valuesForBackgroundShorthand(const ComputedStyle& style, const LayoutObject* layoutObject, Node* styledNode, bool allowVisitedStyle)
+{
+    CSSValueList* ret = CSSValueList::createCommaSeparated();
     const FillLayer* currLayer = &style.backgroundLayers();
     for (; currLayer; currLayer = currLayer->next()) {
-        RawPtr<CSSValueList> list = CSSValueList::createSlashSeparated();
-        RawPtr<CSSValueList> beforeSlash = CSSValueList::createSpaceSeparated();
+        CSSValueList* list = CSSValueList::createSlashSeparated();
+        CSSValueList* beforeSlash = CSSValueList::createSpaceSeparated();
         if (!currLayer->next()) { // color only for final layer
-            RawPtr<CSSValue> value = ComputedStyleCSSValueMapping::get(CSSPropertyBackgroundColor, style, layoutObject, styledNode, allowVisitedStyle);
+            CSSValue* value = ComputedStyleCSSValueMapping::get(CSSPropertyBackgroundColor, style, layoutObject, styledNode, allowVisitedStyle);
             ASSERT(value);
             beforeSlash->append(value);
         }
@@ -489,19 +489,19 @@
         beforeSlash->append(cssValuePool().createValue(currLayer->attachment()));
         beforeSlash->append(createPositionListForLayer(CSSPropertyBackgroundPosition, *currLayer, style));
         list->append(beforeSlash);
-        RawPtr<CSSValueList> afterSlash = CSSValueList::createSpaceSeparated();
+        CSSValueList* afterSlash = CSSValueList::createSpaceSeparated();
         afterSlash->append(valueForFillSize(currLayer->size(), style));
         afterSlash->append(cssValuePool().createValue(currLayer->origin()));
         afterSlash->append(cssValuePool().createValue(currLayer->clip()));
         list->append(afterSlash);
         ret->append(list);
     }
-    return ret.release();
+    return ret;
 }
 
-static RawPtr<CSSValueList> valueForContentPositionAndDistributionWithOverflowAlignment(const StyleContentAlignmentData& data)
+static CSSValueList* valueForContentPositionAndDistributionWithOverflowAlignment(const StyleContentAlignmentData& data)
 {
-    RawPtr<CSSValueList> result = CSSValueList::createSpaceSeparated();
+    CSSValueList* result = CSSValueList::createSpaceSeparated();
     if (data.distribution() != ContentDistributionDefault)
         result->append(CSSPrimitiveValue::create(data.distribution()));
     if (data.distribution() == ContentDistributionDefault || data.position() != ContentPositionNormal)
@@ -510,10 +510,10 @@
         result->append(CSSPrimitiveValue::create(data.overflow()));
     ASSERT(result->length() > 0);
     ASSERT(result->length() <= 3);
-    return result.release();
+    return result;
 }
 
-static RawPtr<CSSPrimitiveValue> valueForLineHeight(const ComputedStyle& style)
+static CSSPrimitiveValue* valueForLineHeight(const ComputedStyle& style)
 {
     Length length = style.lineHeight();
     if (length.isNegative())
@@ -539,48 +539,48 @@
     return CSSValueInvalid;
 }
 
-static RawPtr<CSSValue> valueForFamily(const AtomicString& family)
+static CSSValue* valueForFamily(const AtomicString& family)
 {
     if (CSSValueID familyIdentifier = identifierForFamily(family))
         return cssValuePool().createIdentifierValue(familyIdentifier);
     return cssValuePool().createFontFamilyValue(family.getString());
 }
 
-static RawPtr<CSSValueList> valueForFontFamily(const ComputedStyle& style)
+static CSSValueList* valueForFontFamily(const ComputedStyle& style)
 {
     const FontFamily& firstFamily = style.getFontDescription().family();
-    RawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+    CSSValueList* list = CSSValueList::createCommaSeparated();
     for (const FontFamily* family = &firstFamily; family; family = family->next())
         list->append(valueForFamily(family->family()));
-    return list.release();
+    return list;
 }
 
-static RawPtr<CSSPrimitiveValue> valueForFontSize(const ComputedStyle& style)
+static CSSPrimitiveValue* valueForFontSize(const ComputedStyle& style)
 {
     return zoomAdjustedPixelValue(style.getFontDescription().computedSize(), style);
 }
 
-static RawPtr<CSSPrimitiveValue> valueForFontStretch(const ComputedStyle& style)
+static CSSPrimitiveValue* valueForFontStretch(const ComputedStyle& style)
 {
     return cssValuePool().createValue(style.getFontDescription().stretch());
 }
 
-static RawPtr<CSSPrimitiveValue> valueForFontStyle(const ComputedStyle& style)
+static CSSPrimitiveValue* valueForFontStyle(const ComputedStyle& style)
 {
     return cssValuePool().createValue(style.getFontDescription().style());
 }
 
-static RawPtr<CSSPrimitiveValue> valueForFontVariant(const ComputedStyle& style)
+static CSSPrimitiveValue* valueForFontVariant(const ComputedStyle& style)
 {
     return cssValuePool().createValue(style.getFontDescription().variant());
 }
 
-static RawPtr<CSSPrimitiveValue> valueForFontWeight(const ComputedStyle& style)
+static CSSPrimitiveValue* valueForFontWeight(const ComputedStyle& style)
 {
     return cssValuePool().createValue(style.getFontDescription().weight());
 }
 
-static RawPtr<CSSValue> specifiedValueForGridTrackBreadth(const GridLength& trackBreadth, const ComputedStyle& style)
+static CSSValue* specifiedValueForGridTrackBreadth(const GridLength& trackBreadth, const ComputedStyle& style)
 {
     if (!trackBreadth.isLength())
         return cssValuePool().createValue(trackBreadth.flex(), CSSPrimitiveValue::UnitType::Fraction);
@@ -591,16 +591,16 @@
     return zoomAdjustedPixelValueForLength(trackBreadthLength, style);
 }
 
-static RawPtr<CSSValue> specifiedValueForGridTrackSize(const GridTrackSize& trackSize, const ComputedStyle& style)
+static CSSValue* specifiedValueForGridTrackSize(const GridTrackSize& trackSize, const ComputedStyle& style)
 {
     switch (trackSize.type()) {
     case LengthTrackSizing:
         return specifiedValueForGridTrackBreadth(trackSize.length(), style);
     case MinMaxTrackSizing:
-        RawPtr<CSSFunctionValue> minMaxTrackBreadths = CSSFunctionValue::create(CSSValueMinmax);
+        CSSFunctionValue* minMaxTrackBreadths = CSSFunctionValue::create(CSSValueMinmax);
         minMaxTrackBreadths->append(specifiedValueForGridTrackBreadth(trackSize.minTrackBreadth(), style));
         minMaxTrackBreadths->append(specifiedValueForGridTrackBreadth(trackSize.maxTrackBreadth(), style));
-        return minMaxTrackBreadths.release();
+        return minMaxTrackBreadths;
     }
     ASSERT_NOT_REACHED();
     return nullptr;
@@ -612,13 +612,13 @@
     if (namedGridLines.isEmpty())
         return;
 
-    RawPtr<CSSGridLineNamesValue> lineNames = CSSGridLineNamesValue::create();
+    CSSGridLineNamesValue* lineNames = CSSGridLineNamesValue::create();
     for (size_t j = 0; j < namedGridLines.size(); ++j)
         lineNames->append(CSSCustomIdentValue::create(namedGridLines[j]));
-    list.append(lineNames.release());
+    list.append(lineNames);
 }
 
-static RawPtr<CSSValue> valueForGridTrackList(GridTrackSizingDirection direction, const LayoutObject* layoutObject, const ComputedStyle& style)
+static CSSValue* valueForGridTrackList(GridTrackSizingDirection direction, const LayoutObject* layoutObject, const ComputedStyle& style)
 {
     bool isRowAxis = direction == ForColumns;
     const Vector<GridTrackSize>& trackSizes = isRowAxis ? style.gridTemplateColumns() : style.gridTemplateRows();
@@ -641,7 +641,7 @@
         return cssValuePool().createIdentifierValue(CSSValueNone);
     }
 
-    RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    CSSValueList* list = CSSValueList::createSpaceSeparated();
     size_t insertionIndex;
     if (isLayoutGrid) {
         const Vector<LayoutUnit>& trackPositions = direction == ForColumns ? toLayoutGrid(layoutObject)->columnPositions() : toLayoutGrid(layoutObject)->rowPositions();
@@ -668,10 +668,10 @@
     }
     // Those are the trailing <string>* allowed in the syntax.
     addValuesForNamedGridLinesAtIndex(orderedNamedGridLines, insertionIndex, *list);
-    return list.release();
+    return list;
 }
 
-static RawPtr<CSSValue> valueForGridPosition(const GridPosition& position)
+static CSSValue* valueForGridPosition(const GridPosition& position)
 {
     if (position.isAuto())
         return cssValuePool().createIdentifierValue(CSSValueAuto);
@@ -679,7 +679,7 @@
     if (position.isNamedGridArea())
         return CSSCustomIdentValue::create(position.namedGridLine());
 
-    RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    CSSValueList* list = CSSValueList::createSpaceSeparated();
     if (position.isSpan()) {
         list->append(cssValuePool().createIdentifierValue(CSSValueSpan));
         list->append(cssValuePool().createValue(position.spanPosition(), CSSPrimitiveValue::UnitType::Number));
@@ -701,10 +701,10 @@
     return box->style()->boxSizing() == BoxSizingBorderBox ? box->borderBoxRect() : box->computedCSSContentBoxRect();
 }
 
-static RawPtr<CSSValue> renderTextDecorationFlagsToCSSValue(int textDecoration)
+static CSSValue* renderTextDecorationFlagsToCSSValue(int textDecoration)
 {
     // Blink value is ignored.
-    RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    CSSValueList* list = CSSValueList::createSpaceSeparated();
     if (textDecoration & TextDecorationUnderline)
         list->append(cssValuePool().createIdentifierValue(CSSValueUnderline));
     if (textDecoration & TextDecorationOverline)
@@ -714,10 +714,10 @@
 
     if (!list->length())
         return cssValuePool().createIdentifierValue(CSSValueNone);
-    return list.release();
+    return list;
 }
 
-static RawPtr<CSSValue> valueForTextDecorationStyle(TextDecorationStyle textDecorationStyle)
+static CSSValue* valueForTextDecorationStyle(TextDecorationStyle textDecorationStyle)
 {
     switch (textDecorationStyle) {
     case TextDecorationStyleSolid:
@@ -736,9 +736,9 @@
     return cssValuePool().createExplicitInitialValue();
 }
 
-static RawPtr<CSSValue> touchActionFlagsToCSSValue(TouchAction touchAction)
+static CSSValue* touchActionFlagsToCSSValue(TouchAction touchAction)
 {
-    RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    CSSValueList* list = CSSValueList::createSpaceSeparated();
     if (touchAction == TouchActionAuto) {
         list->append(cssValuePool().createIdentifierValue(CSSValueAuto));
     } else if (touchAction == TouchActionNone) {
@@ -761,12 +761,12 @@
             list->append(cssValuePool().createIdentifierValue(CSSValuePanDown));
     }
     ASSERT(list->length());
-    return list.release();
+    return list;
 }
 
-static RawPtr<CSSValue> valueForWillChange(const Vector<CSSPropertyID>& willChangeProperties, bool willChangeContents, bool willChangeScrollPosition)
+static CSSValue* valueForWillChange(const Vector<CSSPropertyID>& willChangeProperties, bool willChangeContents, bool willChangeScrollPosition)
 {
-    RawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+    CSSValueList* list = CSSValueList::createCommaSeparated();
     if (willChangeContents)
         list->append(cssValuePool().createIdentifierValue(CSSValueContents));
     if (willChangeScrollPosition)
@@ -775,22 +775,22 @@
         list->append(cssValuePool().createIdentifierValue(willChangeProperties[i]));
     if (!list->length())
         list->append(cssValuePool().createIdentifierValue(CSSValueAuto));
-    return list.release();
+    return list;
 }
 
-static RawPtr<CSSValue> valueForAnimationDelay(const CSSTimingData* timingData)
+static CSSValue* valueForAnimationDelay(const CSSTimingData* timingData)
 {
-    RawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+    CSSValueList* list = CSSValueList::createCommaSeparated();
     if (timingData) {
         for (size_t i = 0; i < timingData->delayList().size(); ++i)
             list->append(cssValuePool().createValue(timingData->delayList()[i], CSSPrimitiveValue::UnitType::Seconds));
     } else {
         list->append(cssValuePool().createValue(CSSTimingData::initialDelay(), CSSPrimitiveValue::UnitType::Seconds));
     }
-    return list.release();
+    return list;
 }
 
-static RawPtr<CSSValue> valueForAnimationDirection(Timing::PlaybackDirection direction)
+static CSSValue* valueForAnimationDirection(Timing::PlaybackDirection direction)
 {
     switch (direction) {
     case Timing::PlaybackDirectionNormal:
@@ -807,19 +807,19 @@
     }
 }
 
-static RawPtr<CSSValue> valueForAnimationDuration(const CSSTimingData* timingData)
+static CSSValue* valueForAnimationDuration(const CSSTimingData* timingData)
 {
-    RawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+    CSSValueList* list = CSSValueList::createCommaSeparated();
     if (timingData) {
         for (size_t i = 0; i < timingData->durationList().size(); ++i)
             list->append(cssValuePool().createValue(timingData->durationList()[i], CSSPrimitiveValue::UnitType::Seconds));
     } else {
         list->append(cssValuePool().createValue(CSSTimingData::initialDuration(), CSSPrimitiveValue::UnitType::Seconds));
     }
-    return list.release();
+    return list;
 }
 
-static RawPtr<CSSValue> valueForAnimationFillMode(Timing::FillMode fillMode)
+static CSSValue* valueForAnimationFillMode(Timing::FillMode fillMode)
 {
     switch (fillMode) {
     case Timing::FillModeNone:
@@ -836,14 +836,14 @@
     }
 }
 
-static RawPtr<CSSValue> valueForAnimationIterationCount(double iterationCount)
+static CSSValue* valueForAnimationIterationCount(double iterationCount)
 {
     if (iterationCount == std::numeric_limits<double>::infinity())
         return cssValuePool().createIdentifierValue(CSSValueInfinite);
     return cssValuePool().createValue(iterationCount, CSSPrimitiveValue::UnitType::Number);
 }
 
-static RawPtr<CSSValue> valueForAnimationPlayState(EAnimPlayState playState)
+static CSSValue* valueForAnimationPlayState(EAnimPlayState playState)
 {
     if (playState == AnimPlayStatePlaying)
         return cssValuePool().createIdentifierValue(CSSValueRunning);
@@ -851,7 +851,7 @@
     return cssValuePool().createIdentifierValue(CSSValuePaused);
 }
 
-static RawPtr<CSSValue> createTimingFunctionValue(const TimingFunction* timingFunction)
+static CSSValue* createTimingFunctionValue(const TimingFunction* timingFunction)
 {
     switch (timingFunction->type()) {
     case TimingFunction::kCubicBezierFunction:
@@ -899,21 +899,21 @@
     }
 }
 
-static RawPtr<CSSValue> valueForAnimationTimingFunction(const CSSTimingData* timingData)
+static CSSValue* valueForAnimationTimingFunction(const CSSTimingData* timingData)
 {
-    RawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+    CSSValueList* list = CSSValueList::createCommaSeparated();
     if (timingData) {
         for (size_t i = 0; i < timingData->timingFunctionList().size(); ++i)
             list->append(createTimingFunctionValue(timingData->timingFunctionList()[i].get()));
     } else {
         list->append(createTimingFunctionValue(CSSTimingData::initialTimingFunction().get()));
     }
-    return list.release();
+    return list;
 }
 
-static RawPtr<CSSValueList> valuesForBorderRadiusCorner(LengthSize radius, const ComputedStyle& style)
+static CSSValueList* valuesForBorderRadiusCorner(LengthSize radius, const ComputedStyle& style)
 {
-    RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    CSSValueList* list = CSSValueList::createSpaceSeparated();
     if (radius.width().type() == Percent)
         list->append(cssValuePool().createValue(radius.width().percent(), CSSPrimitiveValue::UnitType::Percentage));
     else
@@ -922,20 +922,20 @@
         list->append(cssValuePool().createValue(radius.height().percent(), CSSPrimitiveValue::UnitType::Percentage));
     else
         list->append(zoomAdjustedPixelValueForLength(radius.height(), style));
-    return list.release();
+    return list;
 }
 
-static RawPtr<CSSValue> valueForBorderRadiusCorner(LengthSize radius, const ComputedStyle& style)
+static CSSValue* valueForBorderRadiusCorner(LengthSize radius, const ComputedStyle& style)
 {
-    RawPtr<CSSValueList> list = valuesForBorderRadiusCorner(radius, style);
+    CSSValueList* list = valuesForBorderRadiusCorner(radius, style);
     if (list->item(0)->equals(*list->item(1)))
         return list->item(0);
-    return list.release();
+    return list;
 }
 
-static RawPtr<CSSFunctionValue> valueForMatrixTransform(const TransformationMatrix& transform, const ComputedStyle& style)
+static CSSFunctionValue* valueForMatrixTransform(const TransformationMatrix& transform, const ComputedStyle& style)
 {
-    RawPtr<CSSFunctionValue> transformValue = nullptr;
+    CSSFunctionValue* transformValue = nullptr;
     if (transform.isAffine()) {
         transformValue = CSSFunctionValue::create(CSSValueMatrix);
 
@@ -969,10 +969,10 @@
         transformValue->append(cssValuePool().createValue(transform.m44(), CSSPrimitiveValue::UnitType::Number));
     }
 
-    return transformValue.release();
+    return transformValue;
 }
 
-static RawPtr<CSSValue> computedTransform(const LayoutObject* layoutObject, const ComputedStyle& style)
+static CSSValue* computedTransform(const LayoutObject* layoutObject, const ComputedStyle& style)
 {
     if (!layoutObject || !style.hasTransform())
         return cssValuePool().createIdentifierValue(CSSValueNone);
@@ -985,13 +985,13 @@
     style.applyTransform(transform, LayoutSize(box.size()), ComputedStyle::ExcludeTransformOrigin, ComputedStyle::ExcludeMotionPath, ComputedStyle::ExcludeIndependentTransformProperties);
 
     // FIXME: Need to print out individual functions (https://bugs.webkit.org/show_bug.cgi?id=23924)
-    RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    CSSValueList* list = CSSValueList::createSpaceSeparated();
     list->append(valueForMatrixTransform(transform, style));
 
-    return list.release();
+    return list;
 }
 
-static RawPtr<CSSValue> createTransitionPropertyValue(const CSSTransitionData::TransitionProperty& property)
+static CSSValue* createTransitionPropertyValue(const CSSTransitionData::TransitionProperty& property)
 {
     if (property.propertyType == CSSTransitionData::TransitionNone)
         return cssValuePool().createIdentifierValue(CSSValueNone);
@@ -1001,16 +1001,16 @@
     return CSSCustomIdentValue::create(getPropertyNameString(property.unresolvedProperty));
 }
 
-static RawPtr<CSSValue> valueForTransitionProperty(const CSSTransitionData* transitionData)
+static CSSValue* valueForTransitionProperty(const CSSTransitionData* transitionData)
 {
-    RawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+    CSSValueList* list = CSSValueList::createCommaSeparated();
     if (transitionData) {
         for (size_t i = 0; i < transitionData->propertyList().size(); ++i)
             list->append(createTransitionPropertyValue(transitionData->propertyList()[i]));
     } else {
         list->append(cssValuePool().createIdentifierValue(CSSValueAll));
     }
-    return list.release();
+    return list;
 }
 
 CSSValueID valueForQuoteType(const QuoteType quoteType)
@@ -1029,20 +1029,20 @@
     return CSSValueInvalid;
 }
 
-static RawPtr<CSSValue> valueForContentData(const ComputedStyle& style)
+static CSSValue* valueForContentData(const ComputedStyle& style)
 {
-    RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    CSSValueList* list = CSSValueList::createSpaceSeparated();
     for (const ContentData* contentData = style.contentData(); contentData; contentData = contentData->next()) {
         if (contentData->isCounter()) {
             const CounterContent* counter = toCounterContentData(contentData)->counter();
             ASSERT(counter);
-            RawPtr<CSSCustomIdentValue> identifier = CSSCustomIdentValue::create(counter->identifier());
-            RawPtr<CSSCustomIdentValue> separator = CSSCustomIdentValue::create(counter->separator());
+            CSSCustomIdentValue* identifier = CSSCustomIdentValue::create(counter->identifier());
+            CSSCustomIdentValue* separator = CSSCustomIdentValue::create(counter->separator());
             CSSValueID listStyleIdent = CSSValueNone;
             if (counter->listStyle() != NoneListStyle)
                 listStyleIdent = static_cast<CSSValueID>(CSSValueDisc + counter->listStyle());
-            RawPtr<CSSPrimitiveValue> listStyle = cssValuePool().createIdentifierValue(listStyleIdent);
-            list->append(CSSCounterValue::create(identifier.release(), listStyle.release(), separator.release()));
+            CSSPrimitiveValue* listStyle = cssValuePool().createIdentifierValue(listStyleIdent);
+            list->append(CSSCounterValue::create(identifier, listStyle, separator));
         } else if (contentData->isImage()) {
             const StyleImage* image = toImageContentData(contentData)->image();
             ASSERT(image);
@@ -1056,16 +1056,16 @@
             ASSERT_NOT_REACHED();
         }
     }
-    return list.release();
+    return list;
 }
 
-static RawPtr<CSSValue> valueForCounterDirectives(const ComputedStyle& style, CSSPropertyID propertyID)
+static CSSValue* valueForCounterDirectives(const ComputedStyle& style, CSSPropertyID propertyID)
 {
     const CounterDirectiveMap* map = style.counterDirectives();
     if (!map)
         return cssValuePool().createIdentifierValue(CSSValueNone);
 
-    RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    CSSValueList* list = CSSValueList::createSpaceSeparated();
     for (const auto& item : *map) {
         bool isValidCounterValue = propertyID == CSSPropertyCounterIncrement ? item.value.isIncrement() : item.value.isReset();
         if (!isValidCounterValue)
@@ -1079,10 +1079,10 @@
     if (!list->length())
         return cssValuePool().createIdentifierValue(CSSValueNone);
 
-    return list.release();
+    return list;
 }
 
-static RawPtr<CSSValue> valueForShape(const ComputedStyle& style, ShapeValue* shapeValue)
+static CSSValue* valueForShape(const ComputedStyle& style, ShapeValue* shapeValue)
 {
     if (!shapeValue)
         return cssValuePool().createIdentifierValue(CSSValueNone);
@@ -1096,21 +1096,21 @@
 
     ASSERT(shapeValue->type() == ShapeValue::Shape);
 
-    RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    CSSValueList* list = CSSValueList::createSpaceSeparated();
     list->append(valueForBasicShape(style, shapeValue->shape()));
     if (shapeValue->cssBox() != BoxMissing)
         list->append(cssValuePool().createValue(shapeValue->cssBox()));
-    return list.release();
+    return list;
 }
 
-static RawPtr<CSSValueList> valuesForSidesShorthand(const StylePropertyShorthand& shorthand, const ComputedStyle& style, const LayoutObject* layoutObject, Node* styledNode, bool allowVisitedStyle)
+static CSSValueList* valuesForSidesShorthand(const StylePropertyShorthand& shorthand, const ComputedStyle& style, const LayoutObject* layoutObject, Node* styledNode, bool allowVisitedStyle)
 {
-    RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    CSSValueList* list = CSSValueList::createSpaceSeparated();
     // Assume the properties are in the usual order top, right, bottom, left.
-    RawPtr<CSSValue> topValue = ComputedStyleCSSValueMapping::get(shorthand.properties()[0], style, layoutObject, styledNode, allowVisitedStyle);
-    RawPtr<CSSValue> rightValue = ComputedStyleCSSValueMapping::get(shorthand.properties()[1], style, layoutObject, styledNode, allowVisitedStyle);
-    RawPtr<CSSValue> bottomValue = ComputedStyleCSSValueMapping::get(shorthand.properties()[2], style, layoutObject, styledNode, allowVisitedStyle);
-    RawPtr<CSSValue> leftValue = ComputedStyleCSSValueMapping::get(shorthand.properties()[3], style, layoutObject, styledNode, allowVisitedStyle);
+    CSSValue* topValue = ComputedStyleCSSValueMapping::get(shorthand.properties()[0], style, layoutObject, styledNode, allowVisitedStyle);
+    CSSValue* rightValue = ComputedStyleCSSValueMapping::get(shorthand.properties()[1], style, layoutObject, styledNode, allowVisitedStyle);
+    CSSValue* bottomValue = ComputedStyleCSSValueMapping::get(shorthand.properties()[2], style, layoutObject, styledNode, allowVisitedStyle);
+    CSSValue* leftValue = ComputedStyleCSSValueMapping::get(shorthand.properties()[3], style, layoutObject, styledNode, allowVisitedStyle);
 
     // All 4 properties must be specified.
     if (!topValue || !rightValue || !bottomValue || !leftValue)
@@ -1120,20 +1120,20 @@
     bool showBottom = !compareCSSValuePtr(topValue, bottomValue) || showLeft;
     bool showRight = !compareCSSValuePtr(topValue, rightValue) || showBottom;
 
-    list->append(topValue.release());
+    list->append(topValue);
     if (showRight)
-        list->append(rightValue.release());
+        list->append(rightValue);
     if (showBottom)
-        list->append(bottomValue.release());
+        list->append(bottomValue);
     if (showLeft)
-        list->append(leftValue.release());
+        list->append(leftValue);
 
-    return list.release();
+    return list;
 }
 
-static RawPtr<CSSValueList> valueForBorderRadiusShorthand(const ComputedStyle& style)
+static CSSValueList* valueForBorderRadiusShorthand(const ComputedStyle& style)
 {
-    RawPtr<CSSValueList> list = CSSValueList::createSlashSeparated();
+    CSSValueList* list = CSSValueList::createSlashSeparated();
 
     bool showHorizontalBottomLeft = style.borderTopRightRadius().width() != style.borderBottomLeftRadius().width();
     bool showHorizontalBottomRight = showHorizontalBottomLeft || (style.borderBottomRightRadius().width() != style.borderTopLeftRadius().width());
@@ -1143,12 +1143,12 @@
     bool showVerticalBottomRight = showVerticalBottomLeft || (style.borderBottomRightRadius().height() != style.borderTopLeftRadius().height());
     bool showVerticalTopRight = showVerticalBottomRight || (style.borderTopRightRadius().height() != style.borderTopLeftRadius().height());
 
-    RawPtr<CSSValueList> topLeftRadius = valuesForBorderRadiusCorner(style.borderTopLeftRadius(), style);
-    RawPtr<CSSValueList> topRightRadius = valuesForBorderRadiusCorner(style.borderTopRightRadius(), style);
-    RawPtr<CSSValueList> bottomRightRadius = valuesForBorderRadiusCorner(style.borderBottomRightRadius(), style);
-    RawPtr<CSSValueList> bottomLeftRadius = valuesForBorderRadiusCorner(style.borderBottomLeftRadius(), style);
+    CSSValueList* topLeftRadius = valuesForBorderRadiusCorner(style.borderTopLeftRadius(), style);
+    CSSValueList* topRightRadius = valuesForBorderRadiusCorner(style.borderTopRightRadius(), style);
+    CSSValueList* bottomRightRadius = valuesForBorderRadiusCorner(style.borderBottomRightRadius(), style);
+    CSSValueList* bottomLeftRadius = valuesForBorderRadiusCorner(style.borderBottomLeftRadius(), style);
 
-    RawPtr<CSSValueList> horizontalRadii = CSSValueList::createSpaceSeparated();
+    CSSValueList* horizontalRadii = CSSValueList::createSpaceSeparated();
     horizontalRadii->append(topLeftRadius->item(0));
     if (showHorizontalTopRight)
         horizontalRadii->append(topRightRadius->item(0));
@@ -1157,9 +1157,9 @@
     if (showHorizontalBottomLeft)
         horizontalRadii->append(bottomLeftRadius->item(0));
 
-    list->append(horizontalRadii.release());
+    list->append(horizontalRadii);
 
-    RawPtr<CSSValueList> verticalRadii = CSSValueList::createSpaceSeparated();
+    CSSValueList* verticalRadii = CSSValueList::createSpaceSeparated();
     verticalRadii->append(topLeftRadius->item(1));
     if (showVerticalTopRight)
         verticalRadii->append(topRightRadius->item(1));
@@ -1169,26 +1169,26 @@
         verticalRadii->append(bottomLeftRadius->item(1));
 
     if (!verticalRadii->equals(*toCSSValueList(list->item(0))))
-        list->append(verticalRadii.release());
+        list->append(verticalRadii);
 
-    return list.release();
+    return list;
 }
 
-static RawPtr<CSSValue> strokeDashArrayToCSSValueList(const SVGDashArray& dashes, const ComputedStyle& style)
+static CSSValue* strokeDashArrayToCSSValueList(const SVGDashArray& dashes, const ComputedStyle& style)
 {
     if (dashes.isEmpty())
         return CSSPrimitiveValue::createIdentifier(CSSValueNone);
 
-    RawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+    CSSValueList* list = CSSValueList::createCommaSeparated();
     for (const Length& dashLength : dashes.vector())
         list->append(zoomAdjustedPixelValueForLength(dashLength, style));
 
-    return list.release();
+    return list;
 }
 
-static RawPtr<CSSValue> paintOrderToCSSValueList(const SVGComputedStyle& svgStyle)
+static CSSValue* paintOrderToCSSValueList(const SVGComputedStyle& svgStyle)
 {
-    RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    CSSValueList* list = CSSValueList::createSpaceSeparated();
     for (int i = 0; i < 3; i++) {
         EPaintOrderType paintOrderType = svgStyle.paintOrderType(i);
         switch (paintOrderType) {
@@ -1204,13 +1204,13 @@
         }
     }
 
-    return list.release();
+    return list;
 }
 
-static RawPtr<CSSValue> adjustSVGPaintForCurrentColor(SVGPaintType paintType, const String& url, const Color& color, const Color& currentColor)
+static CSSValue* adjustSVGPaintForCurrentColor(SVGPaintType paintType, const String& url, const Color& color, const Color& currentColor)
 {
     if (paintType >= SVG_PAINTTYPE_URI_NONE) {
-        RawPtr<CSSValueList> values = CSSValueList::createSpaceSeparated();
+        CSSValueList* values = CSSValueList::createSpaceSeparated();
         values->append(CSSURIValue::create(url));
         if (paintType == SVG_PAINTTYPE_URI_NONE)
             values->append(CSSPrimitiveValue::createIdentifier(CSSValueNone));
@@ -1218,7 +1218,7 @@
             values->append(CSSColorValue::create(currentColor.rgb()));
         else if (paintType == SVG_PAINTTYPE_URI_RGBCOLOR)
             values->append(CSSColorValue::create(color.rgb()));
-        return values.release();
+        return values;
     }
     if (paintType == SVG_PAINTTYPE_NONE)
         return CSSPrimitiveValue::createIdentifier(CSSValueNone);
@@ -1233,37 +1233,37 @@
     return "#" + resource;
 }
 
-RawPtr<CSSValue> ComputedStyleCSSValueMapping::valueForShadowData(const ShadowData& shadow, const ComputedStyle& style, bool useSpread)
+CSSValue* ComputedStyleCSSValueMapping::valueForShadowData(const ShadowData& shadow, const ComputedStyle& style, bool useSpread)
 {
-    RawPtr<CSSPrimitiveValue> x = zoomAdjustedPixelValue(shadow.x(), style);
-    RawPtr<CSSPrimitiveValue> y = zoomAdjustedPixelValue(shadow.y(), style);
-    RawPtr<CSSPrimitiveValue> blur = zoomAdjustedPixelValue(shadow.blur(), style);
-    RawPtr<CSSPrimitiveValue> spread = useSpread ? zoomAdjustedPixelValue(shadow.spread(), style) : RawPtr<CSSPrimitiveValue>(nullptr);
-    RawPtr<CSSPrimitiveValue> shadowStyle = shadow.style() == Normal ? RawPtr<CSSPrimitiveValue>(nullptr) : cssValuePool().createIdentifierValue(CSSValueInset);
-    RawPtr<CSSValue> color = currentColorOrValidColor(style, shadow.color());
-    return CSSShadowValue::create(x.release(), y.release(), blur.release(), spread.release(), shadowStyle.release(), color.release());
+    CSSPrimitiveValue* x = zoomAdjustedPixelValue(shadow.x(), style);
+    CSSPrimitiveValue* y = zoomAdjustedPixelValue(shadow.y(), style);
+    CSSPrimitiveValue* blur = zoomAdjustedPixelValue(shadow.blur(), style);
+    CSSPrimitiveValue* spread = useSpread ? zoomAdjustedPixelValue(shadow.spread(), style) : nullptr;
+    CSSPrimitiveValue* shadowStyle = shadow.style() == Normal ? nullptr : cssValuePool().createIdentifierValue(CSSValueInset);
+    CSSValue* color = currentColorOrValidColor(style, shadow.color());
+    return CSSShadowValue::create(x, y, blur, spread, shadowStyle, color);
 }
 
-RawPtr<CSSValue> ComputedStyleCSSValueMapping::valueForShadowList(const ShadowList* shadowList, const ComputedStyle& style, bool useSpread)
+CSSValue* ComputedStyleCSSValueMapping::valueForShadowList(const ShadowList* shadowList, const ComputedStyle& style, bool useSpread)
 {
     if (!shadowList)
         return cssValuePool().createIdentifierValue(CSSValueNone);
 
-    RawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+    CSSValueList* list = CSSValueList::createCommaSeparated();
     size_t shadowCount = shadowList->shadows().size();
     for (size_t i = 0; i < shadowCount; ++i)
         list->append(valueForShadowData(shadowList->shadows()[i], style, useSpread));
-    return list.release();
+    return list;
 }
 
-RawPtr<CSSValue> ComputedStyleCSSValueMapping::valueForFilter(const ComputedStyle& style, const FilterOperations& filterOperations)
+CSSValue* ComputedStyleCSSValueMapping::valueForFilter(const ComputedStyle& style, const FilterOperations& filterOperations)
 {
     if (filterOperations.operations().isEmpty())
         return cssValuePool().createIdentifierValue(CSSValueNone);
 
-    RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    CSSValueList* list = CSSValueList::createSpaceSeparated();
 
-    RawPtr<CSSFunctionValue> filterValue = nullptr;
+    CSSFunctionValue* filterValue = nullptr;
 
     for (const auto& operation : filterOperations.operations()) {
         FilterOperation* filterOperation = operation.get();
@@ -1320,55 +1320,55 @@
             ASSERT_NOT_REACHED();
             break;
         }
-        list->append(filterValue.release());
+        list->append(filterValue);
     }
 
-    return list.release();
+    return list;
 }
 
-RawPtr<CSSValue> ComputedStyleCSSValueMapping::valueForFont(const ComputedStyle& style)
+CSSValue* ComputedStyleCSSValueMapping::valueForFont(const ComputedStyle& style)
 {
     // Add a slash between size and line-height.
-    RawPtr<CSSValueList> sizeAndLineHeight = CSSValueList::createSlashSeparated();
+    CSSValueList* sizeAndLineHeight = CSSValueList::createSlashSeparated();
     sizeAndLineHeight->append(valueForFontSize(style));
     sizeAndLineHeight->append(valueForLineHeight(style));
 
-    RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    CSSValueList* list = CSSValueList::createSpaceSeparated();
     list->append(valueForFontStyle(style));
     list->append(valueForFontVariant(style));
     list->append(valueForFontWeight(style));
     list->append(valueForFontStretch(style));
-    list->append(sizeAndLineHeight.release());
+    list->append(sizeAndLineHeight);
     list->append(valueForFontFamily(style));
 
-    return list.release();
+    return list;
 }
 
-static RawPtr<CSSValue> valueForScrollSnapDestination(const LengthPoint& destination, const ComputedStyle& style)
+static CSSValue* valueForScrollSnapDestination(const LengthPoint& destination, const ComputedStyle& style)
 {
-    RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    CSSValueList* list = CSSValueList::createSpaceSeparated();
     list->append(zoomAdjustedPixelValueForLength(destination.x(), style));
     list->append(zoomAdjustedPixelValueForLength(destination.y(), style));
-    return list.release();
+    return list;
 }
 
-static RawPtr<CSSValue> valueForScrollSnapPoints(const ScrollSnapPoints& points, const ComputedStyle& style)
+static CSSValue* valueForScrollSnapPoints(const ScrollSnapPoints& points, const ComputedStyle& style)
 {
     if (points.hasRepeat) {
-        RawPtr<CSSFunctionValue> repeat = CSSFunctionValue::create(CSSValueRepeat);
+        CSSFunctionValue* repeat = CSSFunctionValue::create(CSSValueRepeat);
         repeat->append(zoomAdjustedPixelValueForLength(points.repeatOffset, style));
-        return repeat.release();
+        return repeat;
     }
 
     return cssValuePool().createIdentifierValue(CSSValueNone);
 }
 
-static RawPtr<CSSValue> valueForScrollSnapCoordinate(const Vector<LengthPoint>& coordinates, const ComputedStyle& style)
+static CSSValue* valueForScrollSnapCoordinate(const Vector<LengthPoint>& coordinates, const ComputedStyle& style)
 {
     if (coordinates.isEmpty())
         return cssValuePool().createIdentifierValue(CSSValueNone);
 
-    RawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+    CSSValueList* list = CSSValueList::createCommaSeparated();
 
     for (auto& coordinate : coordinates) {
         auto pair = CSSValueList::createSpaceSeparated();
@@ -1377,7 +1377,7 @@
         list->append(pair);
     }
 
-    return list.release();
+    return list;
 }
 
 static EBreak mapToPageBreakValue(EBreak genericBreakValue)
@@ -1416,7 +1416,7 @@
     }
 }
 
-RawPtr<CSSValue> ComputedStyleCSSValueMapping::get(const AtomicString customPropertyName, const ComputedStyle& style)
+CSSValue* ComputedStyleCSSValueMapping::get(const AtomicString customPropertyName, const ComputedStyle& style)
 {
     StyleVariableData* variables = style.variables();
     if (!variables)
@@ -1437,7 +1437,7 @@
     return nullptr;
 }
 
-RawPtr<CSSValue> ComputedStyleCSSValueMapping::get(CSSPropertyID propertyID, const ComputedStyle& style, const LayoutObject* layoutObject, Node* styledNode, bool allowVisitedStyle)
+CSSValue* ComputedStyleCSSValueMapping::get(CSSPropertyID propertyID, const ComputedStyle& style, const LayoutObject* layoutObject, Node* styledNode, bool allowVisitedStyle)
 {
     const SVGComputedStyle& svgStyle = style.svgStyle();
     propertyID = CSSProperty::resolveDirectionAwareProperty(propertyID, style.direction(), style.getWritingMode());
@@ -1449,7 +1449,7 @@
         return allowVisitedStyle ? cssValuePool().createColorValue(style.visitedDependentColor(CSSPropertyBackgroundColor).rgb()) : currentColorOrValidColor(style, style.backgroundColor());
     case CSSPropertyBackgroundImage:
     case CSSPropertyWebkitMaskImage: {
-        RawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+        CSSValueList* list = CSSValueList::createCommaSeparated();
         const FillLayer* currLayer = propertyID == CSSPropertyWebkitMaskImage ? &style.maskLayers() : &style.backgroundLayers();
         for (; currLayer; currLayer = currLayer->next()) {
             if (currLayer->image())
@@ -1457,42 +1457,42 @@
             else
                 list->append(cssValuePool().createIdentifierValue(CSSValueNone));
         }
-        return list.release();
+        return list;
     }
     case CSSPropertyBackgroundSize:
     case CSSPropertyWebkitMaskSize: {
-        RawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+        CSSValueList* list = CSSValueList::createCommaSeparated();
         const FillLayer* currLayer = propertyID == CSSPropertyWebkitMaskSize ? &style.maskLayers() : &style.backgroundLayers();
         for (; currLayer; currLayer = currLayer->next())
             list->append(valueForFillSize(currLayer->size(), style));
-        return list.release();
+        return list;
     }
     case CSSPropertyBackgroundRepeat:
     case CSSPropertyWebkitMaskRepeat: {
-        RawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+        CSSValueList* list = CSSValueList::createCommaSeparated();
         const FillLayer* currLayer = propertyID == CSSPropertyWebkitMaskRepeat ? &style.maskLayers() : &style.backgroundLayers();
         for (; currLayer; currLayer = currLayer->next())
             list->append(valueForFillRepeat(currLayer->repeatX(), currLayer->repeatY()));
-        return list.release();
+        return list;
     }
     case CSSPropertyMaskSourceType: {
-        RawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+        CSSValueList* list = CSSValueList::createCommaSeparated();
         for (const FillLayer* currLayer = &style.maskLayers(); currLayer; currLayer = currLayer->next())
             list->append(valueForFillSourceType(currLayer->maskSourceType()));
-        return list.release();
+        return list;
     }
     case CSSPropertyWebkitMaskComposite: {
-        RawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+        CSSValueList* list = CSSValueList::createCommaSeparated();
         const FillLayer* currLayer = propertyID == CSSPropertyWebkitMaskComposite ? &style.maskLayers() : &style.backgroundLayers();
         for (; currLayer; currLayer = currLayer->next())
             list->append(cssValuePool().createValue(currLayer->composite()));
-        return list.release();
+        return list;
     }
     case CSSPropertyBackgroundAttachment: {
-        RawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+        CSSValueList* list = CSSValueList::createCommaSeparated();
         for (const FillLayer* currLayer = &style.backgroundLayers(); currLayer; currLayer = currLayer->next())
             list->append(cssValuePool().createValue(currLayer->attachment()));
-        return list.release();
+        return list;
     }
     case CSSPropertyBackgroundClip:
     case CSSPropertyBackgroundOrigin:
@@ -1501,47 +1501,47 @@
     case CSSPropertyWebkitMaskClip:
     case CSSPropertyWebkitMaskOrigin: {
         bool isClip = propertyID == CSSPropertyBackgroundClip || propertyID == CSSPropertyWebkitBackgroundClip || propertyID == CSSPropertyWebkitMaskClip;
-        RawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+        CSSValueList* list = CSSValueList::createCommaSeparated();
         const FillLayer* currLayer = (propertyID == CSSPropertyWebkitMaskClip || propertyID == CSSPropertyWebkitMaskOrigin) ? &style.maskLayers() : &style.backgroundLayers();
         for (; currLayer; currLayer = currLayer->next()) {
             EFillBox box = isClip ? currLayer->clip() : currLayer->origin();
             list->append(cssValuePool().createValue(box));
         }
-        return list.release();
+        return list;
     }
     case CSSPropertyBackgroundPosition:
     case CSSPropertyWebkitMaskPosition: {
-        RawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+        CSSValueList* list = CSSValueList::createCommaSeparated();
         const FillLayer* currLayer = propertyID == CSSPropertyWebkitMaskPosition ? &style.maskLayers() : &style.backgroundLayers();
         for (; currLayer; currLayer = currLayer->next())
             list->append(createPositionListForLayer(propertyID, *currLayer, style));
-        return list.release();
+        return list;
     }
     case CSSPropertyBackgroundPositionX:
     case CSSPropertyWebkitMaskPositionX: {
-        RawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+        CSSValueList* list = CSSValueList::createCommaSeparated();
         const FillLayer* currLayer = propertyID == CSSPropertyWebkitMaskPositionX ? &style.maskLayers() : &style.backgroundLayers();
         for (; currLayer; currLayer = currLayer->next())
             list->append(zoomAdjustedPixelValueForLength(currLayer->xPosition(), style));
-        return list.release();
+        return list;
     }
     case CSSPropertyBackgroundPositionY:
     case CSSPropertyWebkitMaskPositionY: {
-        RawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+        CSSValueList* list = CSSValueList::createCommaSeparated();
         const FillLayer* currLayer = propertyID == CSSPropertyWebkitMaskPositionY ? &style.maskLayers() : &style.backgroundLayers();
         for (; currLayer; currLayer = currLayer->next())
             list->append(zoomAdjustedPixelValueForLength(currLayer->yPosition(), style));
-        return list.release();
+        return list;
     }
     case CSSPropertyBorderCollapse:
         if (style.borderCollapse())
             return cssValuePool().createIdentifierValue(CSSValueCollapse);
         return cssValuePool().createIdentifierValue(CSSValueSeparate);
     case CSSPropertyBorderSpacing: {
-        RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+        CSSValueList* list = CSSValueList::createSpaceSeparated();
         list->append(zoomAdjustedPixelValue(style.horizontalBorderSpacing(), style));
         list->append(zoomAdjustedPixelValue(style.verticalBorderSpacing(), style));
-        return list.release();
+        return list;
     }
     case CSSPropertyWebkitBorderHorizontalSpacing:
         return zoomAdjustedPixelValue(style.horizontalBorderSpacing(), style);
@@ -1642,7 +1642,7 @@
         return cssValuePool().createValue(
             style.getTabSize().getPixelSize(1.0), style.getTabSize().isSpaces() ? CSSPrimitiveValue::UnitType::Number : CSSPrimitiveValue::UnitType::Pixels);
     case CSSPropertyCursor: {
-        RawPtr<CSSValueList> list = nullptr;
+        CSSValueList* list = nullptr;
         CursorList* cursors = style.cursors();
         if (cursors && cursors->size() > 0) {
             list = CSSValueList::createCommaSeparated();
@@ -1651,12 +1651,12 @@
                     list->append(image->computedCSSValue());
             }
         }
-        RawPtr<CSSValue> value = cssValuePool().createValue(style.cursor());
+        CSSValue* value = cssValuePool().createValue(style.cursor());
         if (list) {
-            list->append(value.release());
-            return list.release();
+            list->append(value);
+            return list;
         }
-        return value.release();
+        return value;
     }
     case CSSPropertyDirection:
         return cssValuePool().createValue(style.direction());
@@ -1721,16 +1721,16 @@
         const FontFeatureSettings* featureSettings = style.getFontDescription().featureSettings();
         if (!featureSettings || !featureSettings->size())
             return cssValuePool().createIdentifierValue(CSSValueNormal);
-        RawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+        CSSValueList* list = CSSValueList::createCommaSeparated();
         for (unsigned i = 0; i < featureSettings->size(); ++i) {
             const FontFeature& feature = featureSettings->at(i);
-            RawPtr<CSSFontFeatureValue> featureValue = CSSFontFeatureValue::create(feature.tag(), feature.value());
-            list->append(featureValue.release());
+            CSSFontFeatureValue* featureValue = CSSFontFeatureValue::create(feature.tag(), feature.value());
+            list->append(featureValue);
         }
-        return list.release();
+        return list;
     }
     case CSSPropertyGridAutoFlow: {
-        RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+        CSSValueList* list = CSSValueList::createSpaceSeparated();
         switch (style.getGridAutoFlow()) {
         case AutoFlowRow:
         case AutoFlowRowDense:
@@ -1754,7 +1754,7 @@
             break;
         }
 
-        return list.release();
+        return list;
     }
     // Specs mention that getComputedStyle() should return the used value of the property instead of the computed
     // one for grid-definition-{rows|columns} but not for the grid-auto-{rows|columns} as things like
@@ -1996,12 +1996,12 @@
             return nullptr;
         }
         if (style.quotes()->size()) {
-            RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+            CSSValueList* list = CSSValueList::createSpaceSeparated();
             for (int i = 0; i < style.quotes()->size(); i++) {
                 list->append(CSSStringValue::create(style.quotes()->getOpenQuote(i)));
                 list->append(CSSStringValue::create(style.quotes()->getCloseQuote(i)));
             }
-            return list.release();
+            return list;
         }
         return cssValuePool().createIdentifierValue(CSSValueNone);
     case CSSPropertyRight:
@@ -2052,14 +2052,14 @@
         case TextEmphasisMarkDoubleCircle:
         case TextEmphasisMarkTriangle:
         case TextEmphasisMarkSesame: {
-            RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+            CSSValueList* list = CSSValueList::createSpaceSeparated();
             list->append(cssValuePool().createValue(style.getTextEmphasisFill()));
             list->append(cssValuePool().createValue(style.getTextEmphasisMark()));
-            return list.release();
+            return list;
         }
         }
     case CSSPropertyTextIndent: {
-        RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+        CSSValueList* list = CSSValueList::createSpaceSeparated();
         list->append(zoomAdjustedPixelValueForLength(style.textIndent(), style));
         if (RuntimeEnabledFeatures::css3TextEnabled() && (style.getTextIndentLine() == TextIndentEachLine || style.getTextIndentType() == TextIndentHanging)) {
             if (style.getTextIndentLine() == TextIndentEachLine)
@@ -2067,7 +2067,7 @@
             if (style.getTextIndentType() == TextIndentHanging)
                 list->append(cssValuePool().createIdentifierValue(CSSValueHanging));
         }
-        return list.release();
+        return list;
     }
     case CSSPropertyTextShadow:
         return valueForShadowList(style.textShadow(), style, false);
@@ -2156,7 +2156,7 @@
             && historicalLigaturesState == FontDescription::NormalLigaturesState && contextualLigaturesState == FontDescription::NormalLigaturesState)
             return cssValuePool().createIdentifierValue(CSSValueNormal);
 
-        RawPtr<CSSValueList> valueList = CSSValueList::createSpaceSeparated();
+        CSSValueList* valueList = CSSValueList::createSpaceSeparated();
         if (commonLigaturesState != FontDescription::NormalLigaturesState)
             valueList->append(cssValuePool().createIdentifierValue(commonLigaturesState == FontDescription::DisabledLigaturesState ? CSSValueNoCommonLigatures : CSSValueCommonLigatures));
         if (discretionaryLigaturesState != FontDescription::NormalLigaturesState)
@@ -2182,7 +2182,7 @@
     case CSSPropertyAnimationDelay:
         return valueForAnimationDelay(style.animations());
     case CSSPropertyAnimationDirection: {
-        RawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+        CSSValueList* list = CSSValueList::createCommaSeparated();
         const CSSAnimationData* animationData = style.animations();
         if (animationData) {
             for (size_t i = 0; i < animationData->directionList().size(); ++i)
@@ -2190,12 +2190,12 @@
         } else {
             list->append(cssValuePool().createIdentifierValue(CSSValueNormal));
         }
-        return list.release();
+        return list;
     }
     case CSSPropertyAnimationDuration:
         return valueForAnimationDuration(style.animations());
     case CSSPropertyAnimationFillMode: {
-        RawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+        CSSValueList* list = CSSValueList::createCommaSeparated();
         const CSSAnimationData* animationData = style.animations();
         if (animationData) {
             for (size_t i = 0; i < animationData->fillModeList().size(); ++i)
@@ -2203,10 +2203,10 @@
         } else {
             list->append(cssValuePool().createIdentifierValue(CSSValueNone));
         }
-        return list.release();
+        return list;
     }
     case CSSPropertyAnimationIterationCount: {
-        RawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+        CSSValueList* list = CSSValueList::createCommaSeparated();
         const CSSAnimationData* animationData = style.animations();
         if (animationData) {
             for (size_t i = 0; i < animationData->iterationCountList().size(); ++i)
@@ -2214,10 +2214,10 @@
         } else {
             list->append(cssValuePool().createValue(CSSAnimationData::initialIterationCount(), CSSPrimitiveValue::UnitType::Number));
         }
-        return list.release();
+        return list;
     }
     case CSSPropertyAnimationName: {
-        RawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+        CSSValueList* list = CSSValueList::createCommaSeparated();
         const CSSAnimationData* animationData = style.animations();
         if (animationData) {
             for (size_t i = 0; i < animationData->nameList().size(); ++i)
@@ -2225,10 +2225,10 @@
         } else {
             list->append(cssValuePool().createIdentifierValue(CSSValueNone));
         }
-        return list.release();
+        return list;
     }
     case CSSPropertyAnimationPlayState: {
-        RawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+        CSSValueList* list = CSSValueList::createCommaSeparated();
         const CSSAnimationData* animationData = style.animations();
         if (animationData) {
             for (size_t i = 0; i < animationData->playStateList().size(); ++i)
@@ -2236,16 +2236,16 @@
         } else {
             list->append(cssValuePool().createIdentifierValue(CSSValueRunning));
         }
-        return list.release();
+        return list;
     }
     case CSSPropertyAnimationTimingFunction:
         return valueForAnimationTimingFunction(style.animations());
     case CSSPropertyAnimation: {
         const CSSAnimationData* animationData = style.animations();
         if (animationData) {
-            RawPtr<CSSValueList> animationsList = CSSValueList::createCommaSeparated();
+            CSSValueList* animationsList = CSSValueList::createCommaSeparated();
             for (size_t i = 0; i < animationData->nameList().size(); ++i) {
-                RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+                CSSValueList* list = CSSValueList::createSpaceSeparated();
                 list->append(CSSCustomIdentValue::create(animationData->nameList()[i]));
                 list->append(cssValuePool().createValue(CSSTimingData::getRepeated(animationData->durationList(), i), CSSPrimitiveValue::UnitType::Seconds));
                 list->append(createTimingFunctionValue(CSSTimingData::getRepeated(animationData->timingFunctionList(), i).get()));
@@ -2256,10 +2256,10 @@
                 list->append(valueForAnimationPlayState(CSSTimingData::getRepeated(animationData->playStateList(), i)));
                 animationsList->append(list);
             }
-            return animationsList.release();
+            return animationsList;
         }
 
-        RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+        CSSValueList* list = CSSValueList::createSpaceSeparated();
         // animation-name default value.
         list->append(cssValuePool().createIdentifierValue(CSSValueNone));
         list->append(cssValuePool().createValue(CSSAnimationData::initialDuration(), CSSPrimitiveValue::UnitType::Seconds));
@@ -2270,7 +2270,7 @@
         list->append(valueForAnimationFillMode(CSSAnimationData::initialFillMode()));
         // Initial animation-play-state.
         list->append(cssValuePool().createIdentifierValue(CSSValueRunning));
-        return list.release();
+        return list;
     }
     case CSSPropertyWebkitAppearance:
         return cssValuePool().createValue(style.appearance());
@@ -2314,7 +2314,7 @@
             return cssValuePool().createIdentifierValue(CSSValueNone);
         return zoomAdjustedPixelValue(style.perspective(), style);
     case CSSPropertyPerspectiveOrigin: {
-        RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+        CSSValueList* list = CSSValueList::createSpaceSeparated();
         if (layoutObject) {
             LayoutRect box;
             if (layoutObject->isBox())
@@ -2326,7 +2326,7 @@
             list->append(zoomAdjustedPixelValueForLength(style.perspectiveOriginX(), style));
             list->append(zoomAdjustedPixelValueForLength(style.perspectiveOriginY(), style));
         }
-        return list.release();
+        return list;
     }
     case CSSPropertyWebkitRtlOrdering:
         return cssValuePool().createIdentifierValue(style.rtlOrdering() ? CSSValueVisual : CSSValueLogical);
@@ -2347,26 +2347,26 @@
     case CSSPropertyClip: {
         if (style.hasAutoClip())
             return cssValuePool().createIdentifierValue(CSSValueAuto);
-        RawPtr<CSSPrimitiveValue> top = style.clip().top().isAuto()
+        CSSPrimitiveValue* top = style.clip().top().isAuto()
             ? cssValuePool().createIdentifierValue(CSSValueAuto)
             : zoomAdjustedPixelValue(style.clip().top().value(), style);
-        RawPtr<CSSPrimitiveValue> right = style.clip().right().isAuto()
+        CSSPrimitiveValue* right = style.clip().right().isAuto()
             ? cssValuePool().createIdentifierValue(CSSValueAuto)
             : zoomAdjustedPixelValue(style.clip().right().value(), style);
-        RawPtr<CSSPrimitiveValue> bottom = style.clip().bottom().isAuto()
+        CSSPrimitiveValue* bottom = style.clip().bottom().isAuto()
             ? cssValuePool().createIdentifierValue(CSSValueAuto)
             : zoomAdjustedPixelValue(style.clip().bottom().value(), style);
-        RawPtr<CSSPrimitiveValue> left = style.clip().left().isAuto()
+        CSSPrimitiveValue* left = style.clip().left().isAuto()
             ? cssValuePool().createIdentifierValue(CSSValueAuto)
             : zoomAdjustedPixelValue(style.clip().left().value(), style);
-        return CSSQuadValue::create(top.release(), right.release(), bottom.release(), left.release(), CSSQuadValue::SerializeAsRect);
+        return CSSQuadValue::create(top, right, bottom, left, CSSQuadValue::SerializeAsRect);
     }
     case CSSPropertySpeak:
         return cssValuePool().createValue(style.speak());
     case CSSPropertyTransform:
         return computedTransform(layoutObject, style);
     case CSSPropertyTransformOrigin: {
-        RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+        CSSValueList* list = CSSValueList::createSpaceSeparated();
         if (layoutObject) {
             LayoutRect box;
             if (layoutObject->isBox())
@@ -2382,7 +2382,7 @@
             if (style.transformOriginZ() != 0)
                 list->append(zoomAdjustedPixelValue(style.transformOriginZ(), style));
         }
-        return list.release();
+        return list;
     }
     case CSSPropertyTransformStyle:
         return cssValuePool().createIdentifierValue((style.transformStyle3D() == TransformStyle3DPreserve3D) ? CSSValuePreserve3d : CSSValueFlat);
@@ -2397,25 +2397,25 @@
     case CSSPropertyTransition: {
         const CSSTransitionData* transitionData = style.transitions();
         if (transitionData) {
-            RawPtr<CSSValueList> transitionsList = CSSValueList::createCommaSeparated();
+            CSSValueList* transitionsList = CSSValueList::createCommaSeparated();
             for (size_t i = 0; i < transitionData->propertyList().size(); ++i) {
-                RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+                CSSValueList* list = CSSValueList::createSpaceSeparated();
                 list->append(createTransitionPropertyValue(transitionData->propertyList()[i]));
                 list->append(cssValuePool().createValue(CSSTimingData::getRepeated(transitionData->durationList(), i), CSSPrimitiveValue::UnitType::Seconds));
                 list->append(createTimingFunctionValue(CSSTimingData::getRepeated(transitionData->timingFunctionList(), i).get()));
                 list->append(cssValuePool().createValue(CSSTimingData::getRepeated(transitionData->delayList(), i), CSSPrimitiveValue::UnitType::Seconds));
                 transitionsList->append(list);
             }
-            return transitionsList.release();
+            return transitionsList;
         }
 
-        RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+        CSSValueList* list = CSSValueList::createSpaceSeparated();
         // transition-property default value.
         list->append(cssValuePool().createIdentifierValue(CSSValueAll));
         list->append(cssValuePool().createValue(CSSTransitionData::initialDuration(), CSSPrimitiveValue::UnitType::Seconds));
         list->append(createTimingFunctionValue(CSSTransitionData::initialTimingFunction().get()));
         list->append(cssValuePool().createValue(CSSTransitionData::initialDelay(), CSSPrimitiveValue::UnitType::Seconds));
-        return list.release();
+        return list;
     }
     case CSSPropertyPointerEvents:
         return cssValuePool().createValue(style.pointerEvents());
@@ -2464,15 +2464,15 @@
         return cssValuePool().createValue(style.blendMode());
 
     case CSSPropertyBackgroundBlendMode: {
-        RawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+        CSSValueList* list = CSSValueList::createCommaSeparated();
         for (const FillLayer* currLayer = &style.backgroundLayers(); currLayer; currLayer = currLayer->next())
             list->append(cssValuePool().createValue(currLayer->blendMode()));
-        return list.release();
+        return list;
     }
     case CSSPropertyBackground:
         return valuesForBackgroundShorthand(style, layoutObject, styledNode, allowVisitedStyle);
     case CSSPropertyBorder: {
-        RawPtr<CSSValue> value = get(CSSPropertyBorderTop, style, layoutObject, styledNode, allowVisitedStyle);
+        CSSValue* value = get(CSSPropertyBorderTop, style, layoutObject, styledNode, allowVisitedStyle);
         const CSSPropertyID properties[] = {
             CSSPropertyBorderRight,
             CSSPropertyBorderBottom,
@@ -2482,7 +2482,7 @@
             if (!compareCSSValuePtr<CSSValue>(value, get(properties[i], style, layoutObject, styledNode, allowVisitedStyle)))
                 return nullptr;
         }
-        return value.release();
+        return value;
     }
     case CSSPropertyBorderBottom:
         return valuesForShorthandProperty(borderBottomShorthand(), style, layoutObject, styledNode, allowVisitedStyle);
@@ -2531,11 +2531,11 @@
         return zoomAdjustedPixelValueForLength(style.motionOffset(), style);
 
     case CSSPropertyMotionRotation: {
-        RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+        CSSValueList* list = CSSValueList::createSpaceSeparated();
         if (style.motionRotation().type == MotionRotationAuto)
             list->append(cssValuePool().createIdentifierValue(CSSValueAuto));
         list->append(cssValuePool().createValue(style.motionRotation().angle, CSSPrimitiveValue::UnitType::Degrees));
-        return list.release();
+        return list;
     }
 
     // Unimplemented CSS 3 properties (including CSS3 shorthand properties).
@@ -2734,7 +2734,7 @@
         if (!style.translate())
             return cssValuePool().createValue(0, CSSPrimitiveValue::UnitType::Pixels);
 
-        RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+        CSSValueList* list = CSSValueList::createSpaceSeparated();
         if (layoutObject && layoutObject->isBox()) {
             LayoutRect box = toLayoutBox(layoutObject)->borderBoxRect();
             list->append(zoomAdjustedPixelValue(floatValueForLength(style.translate()->x(), box.width().toFloat()), style));
@@ -2753,32 +2753,32 @@
         if (style.translate()->z() != 0)
             list->append(zoomAdjustedPixelValue(style.translate()->z(), style));
 
-        return list.release();
+        return list;
     }
     case CSSPropertyRotate: {
         if (!style.rotate())
             return cssValuePool().createValue(0, CSSPrimitiveValue::UnitType::Degrees);
 
-        RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+        CSSValueList* list = CSSValueList::createSpaceSeparated();
         list->append(cssValuePool().createValue(style.rotate()->angle(), CSSPrimitiveValue::UnitType::Degrees));
         if (style.rotate()->x() != 0 || style.rotate()->y() != 0 || style.rotate()->z() != 1) {
             list->append(cssValuePool().createValue(style.rotate()->x(), CSSPrimitiveValue::UnitType::Number));
             list->append(cssValuePool().createValue(style.rotate()->y(), CSSPrimitiveValue::UnitType::Number));
             list->append(cssValuePool().createValue(style.rotate()->z(), CSSPrimitiveValue::UnitType::Number));
         }
-        return list.release();
+        return list;
     }
     case CSSPropertyScale: {
         if (!style.scale())
             return cssValuePool().createValue(1, CSSPrimitiveValue::UnitType::Number);
-        RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+        CSSValueList* list = CSSValueList::createSpaceSeparated();
         list->append(cssValuePool().createValue(style.scale()->x(), CSSPrimitiveValue::UnitType::Number));
         if (style.scale()->y() == 1 && style.scale()->z() == 1)
-            return list.release();
+            return list;
         list->append(cssValuePool().createValue(style.scale()->y(), CSSPrimitiveValue::UnitType::Number));
         if (style.scale()->z() != 1)
             list->append(cssValuePool().createValue(style.scale()->z(), CSSPrimitiveValue::UnitType::Number));
-        return list.release();
+        return list;
     }
     case CSSPropertyContain: {
         if (!style.contain())
@@ -2786,7 +2786,7 @@
         if (style.contain() == ContainsStrict)
             return cssValuePool().createIdentifierValue(CSSValueStrict);
 
-        RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+        CSSValueList* list = CSSValueList::createSpaceSeparated();
         if (style.containsStyle())
             list->append(cssValuePool().createIdentifierValue(CSSValueStyle));
         if (style.contain() & ContainsLayout)
@@ -2794,16 +2794,16 @@
         if (style.containsPaint())
             list->append(cssValuePool().createIdentifierValue(CSSValuePaint));
         ASSERT(list->length());
-        return list.release();
+        return list;
     }
     case CSSPropertySnapHeight: {
         if (!style.snapHeightUnit())
             return cssValuePool().createValue(0, CSSPrimitiveValue::UnitType::Pixels);
-        RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+        CSSValueList* list = CSSValueList::createSpaceSeparated();
         list->append(cssValuePool().createValue(style.snapHeightUnit(), CSSPrimitiveValue::UnitType::Pixels));
         if (style.snapHeightPosition())
             list->append(cssValuePool().createValue(style.snapHeightPosition(), CSSPrimitiveValue::UnitType::Integer));
-        return list.release();
+        return list;
     }
     case CSSPropertyVariable:
         // Variables are retrieved via get(AtomicString).
diff --git a/third_party/WebKit/Source/core/css/ComputedStyleCSSValueMapping.h b/third_party/WebKit/Source/core/css/ComputedStyleCSSValueMapping.h
index 9e18b78..287548a 100644
--- a/third_party/WebKit/Source/core/css/ComputedStyleCSSValueMapping.h
+++ b/third_party/WebKit/Source/core/css/ComputedStyleCSSValueMapping.h
@@ -24,15 +24,15 @@
     STATIC_ONLY(ComputedStyleCSSValueMapping);
 public:
     // FIXME: Resolve computed auto alignment in applyProperty/ComputedStyle and remove this non-const styledNode parameter.
-    static RawPtr<CSSValue> get(CSSPropertyID, const ComputedStyle&, const LayoutObject* = nullptr, Node* styledNode = nullptr, bool allowVisitedStyle = false);
-    static RawPtr<CSSValue> get(const AtomicString customPropertyName, const ComputedStyle&);
+    static CSSValue* get(CSSPropertyID, const ComputedStyle&, const LayoutObject* = nullptr, Node* styledNode = nullptr, bool allowVisitedStyle = false);
+    static CSSValue* get(const AtomicString customPropertyName, const ComputedStyle&);
     static const HashMap<AtomicString, RefPtr<CSSVariableData>>* getVariables(const ComputedStyle&);
 private:
-    static RawPtr<CSSValue> currentColorOrValidColor(const ComputedStyle&, const StyleColor&);
-    static RawPtr<CSSValue> valueForShadowData(const ShadowData&, const ComputedStyle&, bool useSpread);
-    static RawPtr<CSSValue> valueForShadowList(const ShadowList*, const ComputedStyle&, bool useSpread);
-    static RawPtr<CSSValue> valueForFilter(const ComputedStyle&, const FilterOperations&);
-    static RawPtr<CSSValue> valueForFont(const ComputedStyle&);
+    static CSSValue* currentColorOrValidColor(const ComputedStyle&, const StyleColor&);
+    static CSSValue* valueForShadowData(const ShadowData&, const ComputedStyle&, bool useSpread);
+    static CSSValue* valueForShadowList(const ShadowList*, const ComputedStyle&, bool useSpread);
+    static CSSValue* valueForFilter(const ComputedStyle&, const FilterOperations&);
+    static CSSValue* valueForFont(const ComputedStyle&);
 };
 
 } // namespace blink
diff --git a/third_party/WebKit/Source/core/css/DOMWindowCSS.cpp b/third_party/WebKit/Source/core/css/DOMWindowCSS.cpp
index 3c5aff72..3434d860 100644
--- a/third_party/WebKit/Source/core/css/DOMWindowCSS.cpp
+++ b/third_party/WebKit/Source/core/css/DOMWindowCSS.cpp
@@ -44,8 +44,8 @@
     CSSPropertyID unresolvedProperty = unresolvedCSSPropertyID(property);
     if (unresolvedProperty == CSSPropertyInvalid) {
         if (RuntimeEnabledFeatures::cssVariablesEnabled() && CSSVariableParser::isValidVariableName(property)) {
-            RawPtr<MutableStylePropertySet> dummyStyle = MutableStylePropertySet::create(HTMLStandardMode);
-            return CSSParser::parseValueForCustomProperty(dummyStyle.get(), "--valid", value, false, 0);
+            MutableStylePropertySet* dummyStyle = MutableStylePropertySet::create(HTMLStandardMode);
+            return CSSParser::parseValueForCustomProperty(dummyStyle, "--valid", value, false, 0);
         }
         return false;
     }
@@ -53,8 +53,8 @@
     ASSERT(CSSPropertyMetadata::isEnabledProperty(unresolvedProperty));
 
     // This will return false when !important is present
-    RawPtr<MutableStylePropertySet> dummyStyle = MutableStylePropertySet::create(HTMLStandardMode);
-    return CSSParser::parseValue(dummyStyle.get(), unresolvedProperty, value, false, 0);
+    MutableStylePropertySet* dummyStyle = MutableStylePropertySet::create(HTMLStandardMode);
+    return CSSParser::parseValue(dummyStyle, unresolvedProperty, value, false, 0);
 }
 
 bool DOMWindowCSS::supports(const String& conditionText)
diff --git a/third_party/WebKit/Source/core/css/DocumentFontFaceSet.cpp b/third_party/WebKit/Source/core/css/DocumentFontFaceSet.cpp
index 12ed95f1..eea0072 100644
--- a/third_party/WebKit/Source/core/css/DocumentFontFaceSet.cpp
+++ b/third_party/WebKit/Source/core/css/DocumentFontFaceSet.cpp
@@ -29,7 +29,7 @@
 
 namespace blink {
 
-RawPtr<FontFaceSet> DocumentFontFaceSet::fonts(Document& document)
+FontFaceSet* DocumentFontFaceSet::fonts(Document& document)
 {
     return FontFaceSet::from(document);
 }
diff --git a/third_party/WebKit/Source/core/css/DocumentFontFaceSet.h b/third_party/WebKit/Source/core/css/DocumentFontFaceSet.h
index d16eca3..6cbbf9b 100644
--- a/third_party/WebKit/Source/core/css/DocumentFontFaceSet.h
+++ b/third_party/WebKit/Source/core/css/DocumentFontFaceSet.h
@@ -38,7 +38,7 @@
 class DocumentFontFaceSet {
     STATIC_ONLY(DocumentFontFaceSet);
 public:
-    static RawPtr<FontFaceSet> fonts(Document&);
+    static FontFaceSet* fonts(Document&);
 };
 
 } // namespace blink
diff --git a/third_party/WebKit/Source/core/css/ElementRuleCollector.cpp b/third_party/WebKit/Source/core/css/ElementRuleCollector.cpp
index 0f502af..2f6ed1a 100644
--- a/third_party/WebKit/Source/core/css/ElementRuleCollector.cpp
+++ b/third_party/WebKit/Source/core/css/ElementRuleCollector.cpp
@@ -68,13 +68,13 @@
     return m_result;
 }
 
-RawPtr<StyleRuleList> ElementRuleCollector::matchedStyleRuleList()
+StyleRuleList* ElementRuleCollector::matchedStyleRuleList()
 {
     ASSERT(m_mode == SelectorChecker::CollectingStyleRules);
     return m_styleRuleList.release();
 }
 
-RawPtr<CSSRuleList> ElementRuleCollector::matchedCSSRuleList()
+CSSRuleList* ElementRuleCollector::matchedCSSRuleList()
 {
     ASSERT(m_mode == SelectorChecker::CollectingCSSRules);
     return m_cssRuleList.release();
@@ -254,7 +254,7 @@
     // |parentStyleSheet| is 0 if and only if the |rule| is coming from User Agent. In this case,
     // it is safe to create CSSOM wrappers without parentStyleSheets as they will be used only
     // by inspector which will not try to edit them.
-    RawPtr<CSSRule> cssRule = nullptr;
+    CSSRule* cssRule = nullptr;
     if (parentStyleSheet)
         cssRule = findStyleRule(parentStyleSheet, rule);
     else
diff --git a/third_party/WebKit/Source/core/css/ElementRuleCollector.h b/third_party/WebKit/Source/core/css/ElementRuleCollector.h
index cafcce96..e30a2be 100644
--- a/third_party/WebKit/Source/core/css/ElementRuleCollector.h
+++ b/third_party/WebKit/Source/core/css/ElementRuleCollector.h
@@ -118,8 +118,8 @@
     bool hasAnyMatchingRules(RuleSet*);
 
     const MatchResult& matchedResult() const;
-    RawPtr<StyleRuleList> matchedStyleRuleList();
-    RawPtr<CSSRuleList> matchedCSSRuleList();
+    StyleRuleList* matchedStyleRuleList();
+    CSSRuleList* matchedCSSRuleList();
 
     void collectMatchingRules(const MatchRequest&, CascadeOrder = ignoreCascadeOrder, bool matchingTreeBoundaryRules = false);
     void collectMatchingShadowHostRules(const MatchRequest&, CascadeOrder = ignoreCascadeOrder);
diff --git a/third_party/WebKit/Source/core/css/FontFace.cpp b/third_party/WebKit/Source/core/css/FontFace.cpp
index b84aa66..790110a6 100644
--- a/third_party/WebKit/Source/core/css/FontFace.cpp
+++ b/third_party/WebKit/Source/core/css/FontFace.cpp
@@ -63,13 +63,13 @@
 
 namespace blink {
 
-static RawPtr<CSSValue> parseCSSValue(const Document* document, const String& value, CSSPropertyID propertyID)
+static CSSValue* parseCSSValue(const Document* document, const String& value, CSSPropertyID propertyID)
 {
     CSSParserContext context(*document, UseCounter::getFrom(document));
     return CSSParser::parseFontFaceDescriptor(propertyID, value, context);
 }
 
-RawPtr<FontFace> FontFace::create(ExecutionContext* context, const AtomicString& family, StringOrArrayBufferOrArrayBufferView& source, const FontFaceDescriptors& descriptors)
+FontFace* FontFace::create(ExecutionContext* context, const AtomicString& family, StringOrArrayBufferOrArrayBufferView& source, const FontFaceDescriptors& descriptors)
 {
     if (source.isString())
         return create(context, family, source.getAsString(), descriptors);
@@ -81,45 +81,45 @@
     return nullptr;
 }
 
-RawPtr<FontFace> FontFace::create(ExecutionContext* context, const AtomicString& family, const String& source, const FontFaceDescriptors& descriptors)
+FontFace* FontFace::create(ExecutionContext* context, const AtomicString& family, const String& source, const FontFaceDescriptors& descriptors)
 {
-    RawPtr<FontFace> fontFace = new FontFace(context, family, descriptors);
+    FontFace* fontFace = new FontFace(context, family, descriptors);
 
-    RawPtr<CSSValue> src = parseCSSValue(toDocument(context), source, CSSPropertySrc);
+    CSSValue* src = parseCSSValue(toDocument(context), source, CSSPropertySrc);
     if (!src || !src->isValueList())
         fontFace->setError(DOMException::create(SyntaxError, "The source provided ('" + source + "') could not be parsed as a value list."));
 
     fontFace->initCSSFontFace(toDocument(context), src);
-    return fontFace.release();
+    return fontFace;
 }
 
-RawPtr<FontFace> FontFace::create(ExecutionContext* context, const AtomicString& family, PassRefPtr<DOMArrayBuffer> source, const FontFaceDescriptors& descriptors)
+FontFace* FontFace::create(ExecutionContext* context, const AtomicString& family, PassRefPtr<DOMArrayBuffer> source, const FontFaceDescriptors& descriptors)
 {
-    RawPtr<FontFace> fontFace = new FontFace(context, family, descriptors);
+    FontFace* fontFace = new FontFace(context, family, descriptors);
     fontFace->initCSSFontFace(static_cast<const unsigned char*>(source->data()), source->byteLength());
-    return fontFace.release();
+    return fontFace;
 }
 
-RawPtr<FontFace> FontFace::create(ExecutionContext* context, const AtomicString& family, PassRefPtr<DOMArrayBufferView> source, const FontFaceDescriptors& descriptors)
+FontFace* FontFace::create(ExecutionContext* context, const AtomicString& family, PassRefPtr<DOMArrayBufferView> source, const FontFaceDescriptors& descriptors)
 {
-    RawPtr<FontFace> fontFace = new FontFace(context, family, descriptors);
+    FontFace* fontFace = new FontFace(context, family, descriptors);
     fontFace->initCSSFontFace(static_cast<const unsigned char*>(source->baseAddress()), source->byteLength());
-    return fontFace.release();
+    return fontFace;
 }
 
-RawPtr<FontFace> FontFace::create(Document* document, const StyleRuleFontFace* fontFaceRule)
+FontFace* FontFace::create(Document* document, const StyleRuleFontFace* fontFaceRule)
 {
     const StylePropertySet& properties = fontFaceRule->properties();
 
     // Obtain the font-family property and the src property. Both must be defined.
-    RawPtr<CSSValue> family = properties.getPropertyCSSValue(CSSPropertyFontFamily);
+    CSSValue* family = properties.getPropertyCSSValue(CSSPropertyFontFamily);
     if (!family || (!family->isFontFamilyValue() && !family->isPrimitiveValue()))
         return nullptr;
-    RawPtr<CSSValue> src = properties.getPropertyCSSValue(CSSPropertySrc);
+    CSSValue* src = properties.getPropertyCSSValue(CSSPropertySrc);
     if (!src || !src->isValueList())
         return nullptr;
 
-    RawPtr<FontFace> fontFace = new FontFace(document);
+    FontFace* fontFace = new FontFace(document);
 
     if (fontFace->setFamilyValue(*family)
         && fontFace->setPropertyFromStyle(properties, CSSPropertyFontStyle)
@@ -132,7 +132,7 @@
         && !fontFace->family().isEmpty()
         && fontFace->traits().bitfield()) {
         fontFace->initCSSFontFace(document, src);
-        return fontFace.release();
+        return fontFace;
     }
     return nullptr;
 }
@@ -228,7 +228,7 @@
 
 void FontFace::setPropertyFromString(const Document* document, const String& s, CSSPropertyID propertyID, ExceptionState* exceptionState)
 {
-    RawPtr<CSSValue> value = parseCSSValue(document, s, propertyID);
+    CSSValue* value = parseCSSValue(document, s, propertyID);
     if (value && setPropertyValue(value, propertyID))
         return;
 
@@ -244,7 +244,7 @@
     return setPropertyValue(properties.getPropertyCSSValue(propertyID), propertyID);
 }
 
-bool FontFace::setPropertyValue(RawPtr<CSSValue> value, CSSPropertyID propertyID)
+bool FontFace::setPropertyValue(CSSValue* value, CSSPropertyID propertyID)
 {
     switch (propertyID) {
     case CSSPropertyFontStyle:
@@ -378,7 +378,7 @@
     return fontStatusPromise(scriptState);
 }
 
-void FontFace::loadWithCallback(RawPtr<LoadFontCallback> callback, ExecutionContext* context)
+void FontFace::loadWithCallback(LoadFontCallback* callback, ExecutionContext* context)
 {
     loadInternal(context);
     if (m_status == Loaded)
@@ -502,17 +502,17 @@
     }
 
     FontVariant variant = FontVariantNormal;
-    if (RawPtr<CSSValue> fontVariant = m_variant) {
+    if (CSSValue* fontVariant = m_variant) {
         // font-variant descriptor can be a value list.
         if (fontVariant->isPrimitiveValue()) {
-            RawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+            CSSValueList* list = CSSValueList::createCommaSeparated();
             list->append(fontVariant);
             fontVariant = list;
         } else if (!fontVariant->isValueList()) {
             return 0;
         }
 
-        CSSValueList* variantList = toCSSValueList(fontVariant.get());
+        CSSValueList* variantList = toCSSValueList(fontVariant);
         unsigned numVariants = variantList->length();
         if (!numVariants)
             return 0;
@@ -555,7 +555,7 @@
     return FontDisplayAuto;
 }
 
-static RawPtr<CSSFontFace> createCSSFontFace(FontFace* fontFace, CSSValue* unicodeRange)
+static CSSFontFace* createCSSFontFace(FontFace* fontFace, CSSValue* unicodeRange)
 {
     Vector<UnicodeRange> ranges;
     if (CSSValueList* rangeList = toCSSValueList(unicodeRange)) {
@@ -569,7 +569,7 @@
     return new CSSFontFace(fontFace, ranges);
 }
 
-void FontFace::initCSSFontFace(Document* document, RawPtr<CSSValue> src)
+void FontFace::initCSSFontFace(Document* document, CSSValue* src)
 {
     m_cssFontFace = createCSSFontFace(this, m_unicodeRange.get());
     if (m_error)
@@ -578,22 +578,22 @@
     // Each item in the src property's list is a single CSSFontFaceSource. Put them all into a CSSFontFace.
     ASSERT(src);
     ASSERT(src->isValueList());
-    CSSValueList* srcList = toCSSValueList(src.get());
+    CSSValueList* srcList = toCSSValueList(src);
     int srcLength = srcList->length();
 
     for (int i = 0; i < srcLength; i++) {
         // An item in the list either specifies a string (local font name) or a URL (remote font to download).
         CSSFontFaceSrcValue* item = toCSSFontFaceSrcValue(srcList->item(i));
-        RawPtr<CSSFontFaceSource> source = nullptr;
+        CSSFontFaceSource* source = nullptr;
 
         if (!item->isLocal()) {
             const Settings* settings = document ? document->settings() : nullptr;
             bool allowDownloading = settings && settings->downloadableBinaryFontsEnabled();
             if (allowDownloading && item->isSupportedFormat() && document) {
-                RawPtr<FontResource> fetched = item->fetch(document);
+                FontResource* fetched = item->fetch(document);
                 if (fetched) {
                     FontLoader* fontLoader = document->styleEngine().fontSelector()->fontLoader();
-                    source = new RemoteFontFaceSource(fetched.release(), fontLoader, CSSValueToFontDisplay(m_display.get()));
+                    source = new RemoteFontFaceSource(fetched, fontLoader, CSSValueToFontDisplay(m_display.get()));
                 }
             }
         } else {
@@ -601,7 +601,7 @@
         }
 
         if (source)
-            m_cssFontFace->addSource(source.release());
+            m_cssFontFace->addSource(source);
     }
 
     if (m_display) {
@@ -617,12 +617,12 @@
         return;
 
     RefPtr<SharedBuffer> buffer = SharedBuffer::create(data, size);
-    RawPtr<BinaryDataFontFaceSource> source = new BinaryDataFontFaceSource(buffer.get(), m_otsParseMessage);
+    BinaryDataFontFaceSource* source = new BinaryDataFontFaceSource(buffer.get(), m_otsParseMessage);
     if (source->isValid())
         setLoadStatus(Loaded);
     else
         setError(DOMException::create(SyntaxError, "Invalid font data in ArrayBuffer."));
-    m_cssFontFace->addSource(source.release());
+    m_cssFontFace->addSource(source);
 }
 
 DEFINE_TRACE(FontFace)
diff --git a/third_party/WebKit/Source/core/css/FontFace.h b/third_party/WebKit/Source/core/css/FontFace.h
index bce984d..0aa4022c 100644
--- a/third_party/WebKit/Source/core/css/FontFace.h
+++ b/third_party/WebKit/Source/core/css/FontFace.h
@@ -63,8 +63,8 @@
 public:
     enum LoadStatusType { Unloaded, Loading, Loaded, Error };
 
-    static RawPtr<FontFace> create(ExecutionContext*, const AtomicString& family, StringOrArrayBufferOrArrayBufferView&, const FontFaceDescriptors&);
-    static RawPtr<FontFace> create(Document*, const StyleRuleFontFace*);
+    static FontFace* create(ExecutionContext*, const AtomicString& family, StringOrArrayBufferOrArrayBufferView&, const FontFaceDescriptors&);
+    static FontFace* create(Document*, const StyleRuleFontFace*);
 
     ~FontFace();
 
@@ -108,24 +108,24 @@
         virtual void notifyError(FontFace*) = 0;
         DEFINE_INLINE_VIRTUAL_TRACE() { }
     };
-    void loadWithCallback(RawPtr<LoadFontCallback>, ExecutionContext*);
+    void loadWithCallback(LoadFontCallback*, ExecutionContext*);
 
     // ActiveScriptWrappable.
     bool hasPendingActivity() const final;
 
 private:
-    static RawPtr<FontFace> create(ExecutionContext*, const AtomicString& family, PassRefPtr<DOMArrayBuffer> source, const FontFaceDescriptors&);
-    static RawPtr<FontFace> create(ExecutionContext*, const AtomicString& family, PassRefPtr<DOMArrayBufferView>, const FontFaceDescriptors&);
-    static RawPtr<FontFace> create(ExecutionContext*, const AtomicString& family, const String& source, const FontFaceDescriptors&);
+    static FontFace* create(ExecutionContext*, const AtomicString& family, PassRefPtr<DOMArrayBuffer> source, const FontFaceDescriptors&);
+    static FontFace* create(ExecutionContext*, const AtomicString& family, PassRefPtr<DOMArrayBufferView>, const FontFaceDescriptors&);
+    static FontFace* create(ExecutionContext*, const AtomicString& family, const String& source, const FontFaceDescriptors&);
 
     explicit FontFace(ExecutionContext*);
     FontFace(ExecutionContext*, const AtomicString& family, const FontFaceDescriptors&);
 
-    void initCSSFontFace(Document*, RawPtr<CSSValue> src);
+    void initCSSFontFace(Document*, CSSValue* src);
     void initCSSFontFace(const unsigned char* data, size_t);
     void setPropertyFromString(const Document*, const String&, CSSPropertyID, ExceptionState* = 0);
     bool setPropertyFromStyle(const StylePropertySet&, CSSPropertyID);
-    bool setPropertyValue(RawPtr<CSSValue>, CSSPropertyID);
+    bool setPropertyValue(CSSValue*, CSSPropertyID);
     bool setFamilyValue(const CSSValue&);
     void loadInternal(ExecutionContext*);
     ScriptPromise fontStatusPromise(ScriptState*);
diff --git a/third_party/WebKit/Source/core/css/FontFaceCache.cpp b/third_party/WebKit/Source/core/css/FontFaceCache.cpp
index dc9f9b0c..7330dd4 100644
--- a/third_party/WebKit/Source/core/css/FontFaceCache.cpp
+++ b/third_party/WebKit/Source/core/css/FontFaceCache.cpp
@@ -47,18 +47,15 @@
 {
 }
 
-void FontFaceCache::add(CSSFontSelector* cssFontSelector, const StyleRuleFontFace* fontFaceRule, RawPtr<FontFace> prpFontFace)
+void FontFaceCache::add(CSSFontSelector* cssFontSelector, const StyleRuleFontFace* fontFaceRule, FontFace* fontFace)
 {
-    RawPtr<FontFace> fontFace = prpFontFace;
     if (!m_styleRuleToFontFace.add(fontFaceRule, fontFace).isNewEntry)
         return;
     addFontFace(cssFontSelector, fontFace, true);
 }
 
-void FontFaceCache::addFontFace(CSSFontSelector* cssFontSelector, RawPtr<FontFace> prpFontFace, bool cssConnected)
+void FontFaceCache::addFontFace(CSSFontSelector* cssFontSelector, FontFace* fontFace, bool cssConnected)
 {
-    RawPtr<FontFace> fontFace = prpFontFace;
-
     FamilyToTraitsMap::AddResult traitsResult = m_fontFaces.add(fontFace->family(), nullptr);
     if (!traitsResult.storedValue->value)
         traitsResult.storedValue->value = new TraitsMap;
@@ -94,7 +91,7 @@
     TraitsMap::iterator familyFontFacesIter = familyFontFaces->find(fontFace->traits().bitfield());
     if (familyFontFacesIter == familyFontFaces->end())
         return;
-    RawPtr<CSSSegmentedFontFace> segmentedFontFace = familyFontFacesIter->value;
+    CSSSegmentedFontFace* segmentedFontFace = familyFontFacesIter->value;
 
     segmentedFontFace->removeFontFace(fontFace);
     if (segmentedFontFace->isEmpty()) {
diff --git a/third_party/WebKit/Source/core/css/FontFaceCache.h b/third_party/WebKit/Source/core/css/FontFaceCache.h
index 11ea8555..64f083e 100644
--- a/third_party/WebKit/Source/core/css/FontFaceCache.h
+++ b/third_party/WebKit/Source/core/css/FontFaceCache.h
@@ -48,11 +48,11 @@
 
     // FIXME: Remove CSSFontSelector as argument. Passing CSSFontSelector here is
     // a result of egregious spaghettification in FontFace/FontFaceSet.
-    void add(CSSFontSelector*, const StyleRuleFontFace*, RawPtr<FontFace>);
+    void add(CSSFontSelector*, const StyleRuleFontFace*, FontFace*);
     void remove(const StyleRuleFontFace*);
     void clearCSSConnected();
     void clearAll();
-    void addFontFace(CSSFontSelector*, RawPtr<FontFace>, bool cssConnected);
+    void addFontFace(CSSFontSelector*, FontFace*, bool cssConnected);
     void removeFontFace(FontFace*, bool cssConnected);
 
     // FIXME: It's sort of weird that add/remove uses StyleRuleFontFace* as key,
diff --git a/third_party/WebKit/Source/core/css/FontFaceSet.cpp b/third_party/WebKit/Source/core/css/FontFaceSet.cpp
index 63d430f..2daaefc 100644
--- a/third_party/WebKit/Source/core/css/FontFaceSet.cpp
+++ b/third_party/WebKit/Source/core/css/FontFaceSet.cpp
@@ -49,7 +49,7 @@
 
 class LoadFontPromiseResolver final : public FontFace::LoadFontCallback {
 public:
-    static RawPtr<LoadFontPromiseResolver> create(FontFaceArray faces, ScriptState* scriptState)
+    static LoadFontPromiseResolver* create(FontFaceArray faces, ScriptState* scriptState)
     {
         return new LoadFontPromiseResolver(faces, scriptState);
     }
@@ -235,7 +235,7 @@
     removeFromLoadingFonts(fontFace);
 }
 
-void FontFaceSet::addToLoadingFonts(RawPtr<FontFace> fontFace)
+void FontFaceSet::addToLoadingFonts(FontFace* fontFace)
 {
     if (!m_isLoading) {
         m_isLoading = true;
@@ -247,7 +247,7 @@
     m_loadingFonts.add(fontFace);
 }
 
-void FontFaceSet::removeFromLoadingFonts(RawPtr<FontFace> fontFace)
+void FontFaceSet::removeFromLoadingFonts(FontFace* fontFace)
 {
     m_loadingFonts.remove(fontFace);
     if (m_loadingFonts.isEmpty())
@@ -259,7 +259,7 @@
     return m_ready->promise(scriptState->world());
 }
 
-RawPtr<FontFaceSet> FontFaceSet::addForBinding(ScriptState*, FontFace* fontFace, ExceptionState&)
+FontFaceSet* FontFaceSet::addForBinding(ScriptState*, FontFace* fontFace, ExceptionState&)
 {
     ASSERT(fontFace);
     if (!inActiveDocumentContext())
@@ -352,8 +352,8 @@
         return;
 
     if (m_isLoading) {
-        RawPtr<FontFaceSetLoadEvent> doneEvent = nullptr;
-        RawPtr<FontFaceSetLoadEvent> errorEvent = nullptr;
+        FontFaceSetLoadEvent* doneEvent = nullptr;
+        FontFaceSetLoadEvent* errorEvent = nullptr;
         doneEvent = FontFaceSetLoadEvent::createForFontFaces(EventTypeNames::loadingdone, m_loadedFonts);
         m_loadedFonts.clear();
         if (!m_failedFonts.isEmpty()) {
@@ -391,7 +391,7 @@
             segmentedFontFace->match(text, faces);
     }
 
-    RawPtr<LoadFontPromiseResolver> resolver = LoadFontPromiseResolver::create(faces, scriptState);
+    LoadFontPromiseResolver* resolver = LoadFontPromiseResolver::create(faces, scriptState);
     ScriptPromise promise = resolver->promise();
     resolver->loadFonts(getExecutionContext()); // After this, resolver->promise() may return null.
     return promise;
@@ -435,8 +435,8 @@
         return false;
 
     // Interpret fontString in the same way as the 'font' attribute of CanvasRenderingContext2D.
-    RawPtr<MutableStylePropertySet> parsedStyle = MutableStylePropertySet::create(HTMLStandardMode);
-    CSSParser::parseValue(parsedStyle.get(), CSSPropertyFont, fontString, true, 0);
+    MutableStylePropertySet* parsedStyle = MutableStylePropertySet::create(HTMLStandardMode);
+    CSSParser::parseValue(parsedStyle, CSSPropertyFont, fontString, true, 0);
     if (parsedStyle->isEmpty())
         return false;
 
@@ -494,15 +494,15 @@
     return "FontFaceSet";
 }
 
-RawPtr<FontFaceSet> FontFaceSet::from(Document& document)
+FontFaceSet* FontFaceSet::from(Document& document)
 {
-    RawPtr<FontFaceSet> fonts = static_cast<FontFaceSet*>(Supplement<Document>::from(document, supplementName()));
+    FontFaceSet* fonts = static_cast<FontFaceSet*>(Supplement<Document>::from(document, supplementName()));
     if (!fonts) {
         fonts = FontFaceSet::create(document);
         Supplement<Document>::provideTo(document, supplementName(), fonts);
     }
 
-    return fonts.release();
+    return fonts;
 }
 
 void FontFaceSet::didLayout(Document& document)
diff --git a/third_party/WebKit/Source/core/css/FontFaceSet.h b/third_party/WebKit/Source/core/css/FontFaceSet.h
index 91fd731..666ae96 100644
--- a/third_party/WebKit/Source/core/css/FontFaceSet.h
+++ b/third_party/WebKit/Source/core/css/FontFaceSet.h
@@ -73,7 +73,7 @@
     ScriptPromise load(ScriptState*, const String& font, const String& text);
     ScriptPromise ready(ScriptState*);
 
-    RawPtr<FontFaceSet> addForBinding(ScriptState*, FontFace*, ExceptionState&);
+    FontFaceSet* addForBinding(ScriptState*, FontFace*, ExceptionState&);
     void clearForBinding(ScriptState*, ExceptionState&);
     bool deleteForBinding(ScriptState*, FontFace*, ExceptionState&);
     bool hasForBinding(ScriptState*, FontFace*, ExceptionState&) const;
@@ -96,7 +96,7 @@
     void resume() override;
     void stop() override;
 
-    static RawPtr<FontFaceSet> from(Document&);
+    static FontFaceSet* from(Document&);
     static void didLayout(Document&);
 
     void addFontFacesToFontFaceCache(FontFaceCache*, CSSFontSelector*);
@@ -104,7 +104,7 @@
     DECLARE_VIRTUAL_TRACE();
 
 private:
-    static RawPtr<FontFaceSet> create(Document& document)
+    static FontFaceSet* create(Document& document)
     {
         return new FontFaceSet(document);
     }
@@ -147,8 +147,8 @@
     FontFaceSet(Document&);
 
     bool inActiveDocumentContext() const;
-    void addToLoadingFonts(RawPtr<FontFace>);
-    void removeFromLoadingFonts(RawPtr<FontFace>);
+    void addToLoadingFonts(FontFace*);
+    void removeFromLoadingFonts(FontFace*);
     void fireLoadingEvent();
     void fireDoneEventIfPossible();
     bool resolveFontStyle(const String&, Font&);
diff --git a/third_party/WebKit/Source/core/css/FontFaceSetLoadEvent.h b/third_party/WebKit/Source/core/css/FontFaceSetLoadEvent.h
index bd4357d..da74072 100644
--- a/third_party/WebKit/Source/core/css/FontFaceSetLoadEvent.h
+++ b/third_party/WebKit/Source/core/css/FontFaceSetLoadEvent.h
@@ -43,17 +43,17 @@
 class FontFaceSetLoadEvent final : public Event {
     DEFINE_WRAPPERTYPEINFO();
 public:
-    static RawPtr<FontFaceSetLoadEvent> create()
+    static FontFaceSetLoadEvent* create()
     {
         return new FontFaceSetLoadEvent();
     }
 
-    static RawPtr<FontFaceSetLoadEvent> create(const AtomicString& type, const FontFaceSetLoadEventInit& initializer)
+    static FontFaceSetLoadEvent* create(const AtomicString& type, const FontFaceSetLoadEventInit& initializer)
     {
         return new FontFaceSetLoadEvent(type, initializer);
     }
 
-    static RawPtr<FontFaceSetLoadEvent> createForFontFaces(const AtomicString& type, const FontFaceArray& fontfaces = FontFaceArray())
+    static FontFaceSetLoadEvent* createForFontFaces(const AtomicString& type, const FontFaceArray& fontfaces = FontFaceArray())
     {
         return new FontFaceSetLoadEvent(type, fontfaces);
     }
diff --git a/third_party/WebKit/Source/core/css/FontLoader.cpp b/third_party/WebKit/Source/core/css/FontLoader.cpp
index 98d9ce9..94b4e16 100644
--- a/third_party/WebKit/Source/core/css/FontLoader.cpp
+++ b/third_party/WebKit/Source/core/css/FontLoader.cpp
@@ -14,7 +14,7 @@
 
 struct FontLoader::FontToLoad : public GarbageCollectedFinalized<FontLoader::FontToLoad> {
 public:
-    static RawPtr<FontToLoad> create(FontResource* fontResource, Document& document)
+    static FontToLoad* create(FontResource* fontResource, Document& document)
     {
         return new FontToLoad(fontResource, document);
     }
diff --git a/third_party/WebKit/Source/core/css/FontLoader.h b/third_party/WebKit/Source/core/css/FontLoader.h
index 181630a8..b7d516d 100644
--- a/third_party/WebKit/Source/core/css/FontLoader.h
+++ b/third_party/WebKit/Source/core/css/FontLoader.h
@@ -18,7 +18,7 @@
 
 class FontLoader : public GarbageCollectedFinalized<FontLoader> {
 public:
-    static RawPtr<FontLoader> create(CSSFontSelector* fontSelector, Document* document)
+    static FontLoader* create(CSSFontSelector* fontSelector, Document* document)
     {
         return new FontLoader(fontSelector, document);
     }
diff --git a/third_party/WebKit/Source/core/css/KeyframeStyleRuleCSSStyleDeclaration.h b/third_party/WebKit/Source/core/css/KeyframeStyleRuleCSSStyleDeclaration.h
index f0b3897..eb6cd0b5 100644
--- a/third_party/WebKit/Source/core/css/KeyframeStyleRuleCSSStyleDeclaration.h
+++ b/third_party/WebKit/Source/core/css/KeyframeStyleRuleCSSStyleDeclaration.h
@@ -13,7 +13,7 @@
 
 class KeyframeStyleRuleCSSStyleDeclaration final : public StyleRuleCSSStyleDeclaration {
 public:
-    static RawPtr<KeyframeStyleRuleCSSStyleDeclaration> create(MutableStylePropertySet& propertySet, CSSKeyframeRule* parentRule)
+    static KeyframeStyleRuleCSSStyleDeclaration* create(MutableStylePropertySet& propertySet, CSSKeyframeRule* parentRule)
     {
         return new KeyframeStyleRuleCSSStyleDeclaration(propertySet, parentRule);
     }
diff --git a/third_party/WebKit/Source/core/css/MediaList.cpp b/third_party/WebKit/Source/core/css/MediaList.cpp
index ee24959..5650a5b 100644
--- a/third_party/WebKit/Source/core/css/MediaList.cpp
+++ b/third_party/WebKit/Source/core/css/MediaList.cpp
@@ -59,7 +59,7 @@
         m_queries[i] = o.m_queries[i]->copy();
 }
 
-RawPtr<MediaQuerySet> MediaQuerySet::create(const String& mediaString)
+MediaQuerySet* MediaQuerySet::create(const String& mediaString)
 {
     if (mediaString.isEmpty())
         return MediaQuerySet::create();
@@ -67,7 +67,7 @@
     return MediaQueryParser::parseMediaQuerySet(mediaString);
 }
 
-RawPtr<MediaQuerySet> MediaQuerySet::createOffMainThread(const String& mediaString)
+MediaQuerySet* MediaQuerySet::createOffMainThread(const String& mediaString)
 {
     if (mediaString.isEmpty())
         return MediaQuerySet::create();
@@ -77,7 +77,7 @@
 
 bool MediaQuerySet::set(const String& mediaString)
 {
-    RawPtr<MediaQuerySet> result = create(mediaString);
+    MediaQuerySet* result = create(mediaString);
     m_queries.swap(result->m_queries);
     return true;
 }
@@ -87,13 +87,13 @@
     // To "parse a media query" for a given string means to follow "the parse
     // a media query list" steps and return "null" if more than one media query
     // is returned, or else the returned media query.
-    RawPtr<MediaQuerySet> result = create(queryString);
+    MediaQuerySet* result = create(queryString);
 
     // Only continue if exactly one media query is found, as described above.
     if (result->m_queries.size() != 1)
         return true;
 
-    RawPtr<MediaQuery> newQuery = result->m_queries[0].release();
+    MediaQuery* newQuery = result->m_queries[0].release();
     ASSERT(newQuery);
 
     // If comparing with any of the media queries in the collection of media
@@ -104,7 +104,7 @@
             return true;
     }
 
-    m_queries.append(newQuery.release());
+    m_queries.append(newQuery);
     return true;
 }
 
@@ -113,13 +113,13 @@
     // To "parse a media query" for a given string means to follow "the parse
     // a media query list" steps and return "null" if more than one media query
     // is returned, or else the returned media query.
-    RawPtr<MediaQuerySet> result = create(queryStringToRemove);
+    MediaQuerySet* result = create(queryStringToRemove);
 
     // Only continue if exactly one media query is found, as described above.
     if (result->m_queries.size() != 1)
         return true;
 
-    RawPtr<MediaQuery> newQuery = result->m_queries[0].release();
+    MediaQuery* newQuery = result->m_queries[0].release();
     ASSERT(newQuery);
 
     // Remove any media query from the collection of media queries for which
@@ -137,7 +137,7 @@
     return found;
 }
 
-void MediaQuerySet::addMediaQuery(RawPtr<MediaQuery> mediaQuery)
+void MediaQuerySet::addMediaQuery(MediaQuery* mediaQuery)
 {
     m_queries.append(mediaQuery);
 }
diff --git a/third_party/WebKit/Source/core/css/MediaList.h b/third_party/WebKit/Source/core/css/MediaList.h
index 2c480f4d..f55f00a 100644
--- a/third_party/WebKit/Source/core/css/MediaList.h
+++ b/third_party/WebKit/Source/core/css/MediaList.h
@@ -41,24 +41,24 @@
 
 class CORE_EXPORT MediaQuerySet : public GarbageCollected<MediaQuerySet> {
 public:
-    static RawPtr<MediaQuerySet> create()
+    static MediaQuerySet* create()
     {
         return new MediaQuerySet();
     }
-    static RawPtr<MediaQuerySet> create(const String& mediaString);
-    static RawPtr<MediaQuerySet> createOffMainThread(const String& mediaString);
+    static MediaQuerySet* create(const String& mediaString);
+    static MediaQuerySet* createOffMainThread(const String& mediaString);
 
     bool set(const String&);
     bool add(const String&);
     bool remove(const String&);
 
-    void addMediaQuery(RawPtr<MediaQuery>);
+    void addMediaQuery(MediaQuery*);
 
     const HeapVector<Member<MediaQuery>>& queryVector() const { return m_queries; }
 
     String mediaText() const;
 
-    RawPtr<MediaQuerySet> copy() const { return new MediaQuerySet(*this); }
+    MediaQuerySet* copy() const { return new MediaQuerySet(*this); }
 
     DECLARE_TRACE();
 
@@ -72,12 +72,12 @@
 class MediaList final : public GarbageCollected<MediaList>, public ScriptWrappable {
     DEFINE_WRAPPERTYPEINFO();
 public:
-    static RawPtr<MediaList> create(MediaQuerySet* mediaQueries, CSSStyleSheet* parentSheet)
+    static MediaList* create(MediaQuerySet* mediaQueries, CSSStyleSheet* parentSheet)
     {
         return new MediaList(mediaQueries, parentSheet);
     }
 
-    static RawPtr<MediaList> create(MediaQuerySet* mediaQueries, CSSRule* parentRule)
+    static MediaList* create(MediaQuerySet* mediaQueries, CSSRule* parentRule)
     {
         return new MediaList(mediaQueries, parentRule);
     }
diff --git a/third_party/WebKit/Source/core/css/MediaQuery.cpp b/third_party/WebKit/Source/core/css/MediaQuery.cpp
index 5b553880..4080e0a 100644
--- a/third_party/WebKit/Source/core/css/MediaQuery.cpp
+++ b/third_party/WebKit/Source/core/css/MediaQuery.cpp
@@ -74,12 +74,12 @@
     return codePointCompare(a->serialize(), b->serialize()) < 0;
 }
 
-RawPtr<MediaQuery> MediaQuery::createNotAll()
+MediaQuery* MediaQuery::createNotAll()
 {
     return new MediaQuery(MediaQuery::Not, MediaTypeNames::all, ExpressionHeapVector());
 }
 
-RawPtr<MediaQuery> MediaQuery::create(RestrictorType restrictor, String mediaType, ExpressionHeapVector expressions)
+MediaQuery* MediaQuery::create(RestrictorType restrictor, String mediaType, ExpressionHeapVector expressions)
 {
     return new MediaQuery(restrictor, std::move(mediaType), std::move(expressions));
 }
diff --git a/third_party/WebKit/Source/core/css/MediaQuery.h b/third_party/WebKit/Source/core/css/MediaQuery.h
index 08a997a..18719e7 100644
--- a/third_party/WebKit/Source/core/css/MediaQuery.h
+++ b/third_party/WebKit/Source/core/css/MediaQuery.h
@@ -48,8 +48,8 @@
         Only, Not, None
     };
 
-    static RawPtr<MediaQuery> create(RestrictorType, String mediaType, ExpressionHeapVector);
-    static RawPtr<MediaQuery> createNotAll();
+    static MediaQuery* create(RestrictorType, String mediaType, ExpressionHeapVector);
+    static MediaQuery* createNotAll();
 
     ~MediaQuery();
 
@@ -59,7 +59,7 @@
     bool operator==(const MediaQuery& other) const;
     String cssText() const;
 
-    RawPtr<MediaQuery> copy() const { return new MediaQuery(*this); }
+    MediaQuery* copy() const { return new MediaQuery(*this); }
 
     DECLARE_TRACE();
 
diff --git a/third_party/WebKit/Source/core/css/MediaQueryEvaluatorTest.cpp b/third_party/WebKit/Source/core/css/MediaQueryEvaluatorTest.cpp
index b0b905d..2cb2eb368 100644
--- a/third_party/WebKit/Source/core/css/MediaQueryEvaluatorTest.cpp
+++ b/third_party/WebKit/Source/core/css/MediaQueryEvaluatorTest.cpp
@@ -148,7 +148,7 @@
     data.mediaType = MediaTypeNames::screen;
     data.strictMode = true;
     data.displayMode = WebDisplayModeBrowser;
-    RawPtr<MediaValues> mediaValues = MediaValuesCached::create(data);
+    MediaValues* mediaValues = MediaValuesCached::create(data);
 
     MediaQueryEvaluator mediaQueryEvaluator(*mediaValues);
     testMQEvaluator(screenTestCases, mediaQueryEvaluator);
@@ -174,12 +174,12 @@
 TEST(MediaQueryEvaluatorTest, DynamicNoView)
 {
     OwnPtr<DummyPageHolder> pageHolder = DummyPageHolder::create(IntSize(500, 500));
-    RawPtr<LocalFrame> frame = &pageHolder->frame();
+    LocalFrame* frame = &pageHolder->frame();
     pageHolder.clear();
     ASSERT_EQ(nullptr, frame->view());
-    MediaQueryEvaluator mediaQueryEvaluator(frame.get());
-    RawPtr<MediaQuerySet> querySet = MediaQuerySet::create("foobar");
-    EXPECT_FALSE(mediaQueryEvaluator.eval(querySet.get()));
+    MediaQueryEvaluator mediaQueryEvaluator(frame);
+    MediaQuerySet* querySet = MediaQuerySet::create("foobar");
+    EXPECT_FALSE(mediaQueryEvaluator.eval(querySet));
 }
 
 TEST(MediaQueryEvaluatorTest, CachedFloatViewport)
@@ -187,7 +187,7 @@
     MediaValuesCached::MediaValuesCachedData data;
     data.viewportWidth = 600.5;
     data.viewportHeight = 700.125;
-    RawPtr<MediaValues> mediaValues = MediaValuesCached::create(data);
+    MediaValues* mediaValues = MediaValuesCached::create(data);
 
     MediaQueryEvaluator mediaQueryEvaluator(*mediaValues);
     testMQEvaluator(floatViewportTestCases, mediaQueryEvaluator);
diff --git a/third_party/WebKit/Source/core/css/MediaQueryExp.cpp b/third_party/WebKit/Source/core/css/MediaQueryExp.cpp
index b429550..f7a1711 100644
--- a/third_party/WebKit/Source/core/css/MediaQueryExp.cpp
+++ b/third_party/WebKit/Source/core/css/MediaQueryExp.cpp
@@ -203,7 +203,7 @@
 {
 }
 
-RawPtr<MediaQueryExp> MediaQueryExp::createIfValid(const String& mediaFeature, const Vector<CSSParserToken, 4>& tokenList)
+MediaQueryExp* MediaQueryExp::createIfValid(const String& mediaFeature, const Vector<CSSParserToken, 4>& tokenList)
 {
     ASSERT(!mediaFeature.isNull());
 
diff --git a/third_party/WebKit/Source/core/css/MediaQueryExp.h b/third_party/WebKit/Source/core/css/MediaQueryExp.h
index 39bbefce..266a3eb 100644
--- a/third_party/WebKit/Source/core/css/MediaQueryExp.h
+++ b/third_party/WebKit/Source/core/css/MediaQueryExp.h
@@ -82,7 +82,7 @@
 
 class CORE_EXPORT MediaQueryExp  : public GarbageCollectedFinalized<MediaQueryExp> {
 public:
-    static RawPtr<MediaQueryExp> createIfValid(const String& mediaFeature, const Vector<CSSParserToken, 4>&);
+    static MediaQueryExp* createIfValid(const String& mediaFeature, const Vector<CSSParserToken, 4>&);
     ~MediaQueryExp();
 
     const String& mediaFeature() const { return m_mediaFeature; }
@@ -97,7 +97,7 @@
 
     String serialize() const;
 
-    RawPtr<MediaQueryExp> copy() const { return new MediaQueryExp(*this); }
+    MediaQueryExp* copy() const { return new MediaQueryExp(*this); }
 
     MediaQueryExp(const MediaQueryExp& other);
 
diff --git a/third_party/WebKit/Source/core/css/MediaQueryList.cpp b/third_party/WebKit/Source/core/css/MediaQueryList.cpp
index 8595543..0779b2a7 100644
--- a/third_party/WebKit/Source/core/css/MediaQueryList.cpp
+++ b/third_party/WebKit/Source/core/css/MediaQueryList.cpp
@@ -27,14 +27,14 @@
 
 namespace blink {
 
-RawPtr<MediaQueryList> MediaQueryList::create(ExecutionContext* context, RawPtr<MediaQueryMatcher> matcher, RawPtr<MediaQuerySet> media)
+MediaQueryList* MediaQueryList::create(ExecutionContext* context, MediaQueryMatcher* matcher, MediaQuerySet* media)
 {
-    RawPtr<MediaQueryList> list = new MediaQueryList(context, matcher, media);
+    MediaQueryList* list = new MediaQueryList(context, matcher, media);
     list->suspendIfNeeded();
-    return list.release();
+    return list;
 }
 
-MediaQueryList::MediaQueryList(ExecutionContext* context, RawPtr<MediaQueryMatcher> matcher, RawPtr<MediaQuerySet> media)
+MediaQueryList::MediaQueryList(ExecutionContext* context, MediaQueryMatcher* matcher, MediaQuerySet* media)
     : ActiveScriptWrappable(this)
     , ActiveDOMObject(context)
     , m_matcher(matcher)
@@ -58,7 +58,7 @@
     return m_media->mediaText();
 }
 
-void MediaQueryList::addDeprecatedListener(RawPtr<EventListener> listener)
+void MediaQueryList::addDeprecatedListener(EventListener* listener)
 {
     if (!listener)
         return;
@@ -66,7 +66,7 @@
     addEventListener(EventTypeNames::change, listener, false);
 }
 
-void MediaQueryList::removeDeprecatedListener(RawPtr<EventListener> listener)
+void MediaQueryList::removeDeprecatedListener(EventListener* listener)
 {
     if (!listener)
         return;
@@ -74,7 +74,7 @@
     removeEventListener(EventTypeNames::change, listener, false);
 }
 
-void MediaQueryList::addListener(RawPtr<MediaQueryListListener> listener)
+void MediaQueryList::addListener(MediaQueryListListener* listener)
 {
     if (!listener)
         return;
@@ -82,12 +82,11 @@
     m_listeners.add(listener);
 }
 
-void MediaQueryList::removeListener(RawPtr<MediaQueryListListener> listener)
+void MediaQueryList::removeListener(MediaQueryListListener* listener)
 {
     if (!listener)
         return;
 
-    RawPtr<MediaQueryList> protect(this);
     m_listeners.remove(listener);
 }
 
@@ -98,8 +97,6 @@
 
 void MediaQueryList::stop()
 {
-    // m_listeners.clear() can drop the last ref to this MediaQueryList.
-    RawPtr<MediaQueryList> protect(this);
     m_listeners.clear();
     removeAllEventListeners();
 }
diff --git a/third_party/WebKit/Source/core/css/MediaQueryList.h b/third_party/WebKit/Source/core/css/MediaQueryList.h
index 26bab243f..88011a9 100644
--- a/third_party/WebKit/Source/core/css/MediaQueryList.h
+++ b/third_party/WebKit/Source/core/css/MediaQueryList.h
@@ -47,7 +47,7 @@
     DEFINE_WRAPPERTYPEINFO();
     USING_GARBAGE_COLLECTED_MIXIN(MediaQueryList);
 public:
-    static RawPtr<MediaQueryList> create(ExecutionContext*, RawPtr<MediaQueryMatcher>, RawPtr<MediaQuerySet>);
+    static MediaQueryList* create(ExecutionContext*, MediaQueryMatcher*, MediaQuerySet*);
     ~MediaQueryList() override;
 
     String media() const;
@@ -57,12 +57,12 @@
 
     // These two functions are provided for compatibility with JS code
     // written before the change listener became a DOM event.
-    void addDeprecatedListener(RawPtr<EventListener>);
-    void removeDeprecatedListener(RawPtr<EventListener>);
+    void addDeprecatedListener(EventListener*);
+    void removeDeprecatedListener(EventListener*);
 
     // C++ code can use these functions to listen to changes instead of having to use DOM event listeners.
-    void addListener(RawPtr<MediaQueryListListener>);
-    void removeListener(RawPtr<MediaQueryListListener>);
+    void addListener(MediaQueryListListener*);
+    void removeListener(MediaQueryListListener*);
 
     // Will return true if a DOM event should be scheduled.
     bool mediaFeaturesChanged(HeapVector<Member<MediaQueryListListener>>* listenersToNotify);
@@ -79,7 +79,7 @@
     ExecutionContext* getExecutionContext() const override;
 
 private:
-    MediaQueryList(ExecutionContext*, RawPtr<MediaQueryMatcher>, RawPtr<MediaQuerySet>);
+    MediaQueryList(ExecutionContext*, MediaQueryMatcher*, MediaQuerySet*);
 
     bool updateMatches();
 
diff --git a/third_party/WebKit/Source/core/css/MediaQueryListEvent.h b/third_party/WebKit/Source/core/css/MediaQueryListEvent.h
index 22315f8b..6924bbff 100644
--- a/third_party/WebKit/Source/core/css/MediaQueryListEvent.h
+++ b/third_party/WebKit/Source/core/css/MediaQueryListEvent.h
@@ -14,22 +14,22 @@
 class MediaQueryListEvent final : public Event {
     DEFINE_WRAPPERTYPEINFO();
 public:
-    static RawPtr<MediaQueryListEvent> create()
+    static MediaQueryListEvent* create()
     {
         return new MediaQueryListEvent;
     }
 
-    static RawPtr<MediaQueryListEvent> create(RawPtr<MediaQueryList> list)
+    static MediaQueryListEvent* create(MediaQueryList* list)
     {
         return new MediaQueryListEvent(list);
     }
 
-    static RawPtr<MediaQueryListEvent> create(const String& media, bool matches)
+    static MediaQueryListEvent* create(const String& media, bool matches)
     {
         return new MediaQueryListEvent(media, matches);
     }
 
-    static RawPtr<MediaQueryListEvent> create(const AtomicString& eventType, const MediaQueryListEventInit& initializer)
+    static MediaQueryListEvent* create(const AtomicString& eventType, const MediaQueryListEventInit& initializer)
     {
         return new MediaQueryListEvent(eventType, initializer);
     }
@@ -54,7 +54,7 @@
         , m_media(media)
         , m_matches(matches) { }
 
-    explicit MediaQueryListEvent(RawPtr<MediaQueryList> list)
+    explicit MediaQueryListEvent(MediaQueryList* list)
         : Event(EventTypeNames::change, false, false)
         , m_mediaQueryList(list)
         , m_matches(false) { }
diff --git a/third_party/WebKit/Source/core/css/MediaQueryListTest.cpp b/third_party/WebKit/Source/core/css/MediaQueryListTest.cpp
index 7605e2e4..ba52cd9 100644
--- a/third_party/WebKit/Source/core/css/MediaQueryListTest.cpp
+++ b/third_party/WebKit/Source/core/css/MediaQueryListTest.cpp
@@ -23,8 +23,8 @@
 
 TEST(MediaQueryListTest, CrashInStop)
 {
-    RawPtr<Document> document = Document::create();
-    RawPtr<MediaQueryList> list = MediaQueryList::create(document.get(), MediaQueryMatcher::create(*document), MediaQuerySet::create());
+    Document* document = Document::create();
+    MediaQueryList* list = MediaQueryList::create(document, MediaQueryMatcher::create(*document), MediaQuerySet::create());
     list->addListener(new TestListener());
     list->stop();
     // This test passes if it's not crashed.
diff --git a/third_party/WebKit/Source/core/css/MediaQueryMatcher.cpp b/third_party/WebKit/Source/core/css/MediaQueryMatcher.cpp
index e7674732..a624d51 100644
--- a/third_party/WebKit/Source/core/css/MediaQueryMatcher.cpp
+++ b/third_party/WebKit/Source/core/css/MediaQueryMatcher.cpp
@@ -32,7 +32,7 @@
 
 namespace blink {
 
-RawPtr<MediaQueryMatcher> MediaQueryMatcher::create(Document& document)
+MediaQueryMatcher* MediaQueryMatcher::create(Document& document)
 {
     return new MediaQueryMatcher(document);
 }
@@ -53,7 +53,7 @@
     m_evaluator = nullptr;
 }
 
-RawPtr<MediaQueryEvaluator> MediaQueryMatcher::createEvaluator() const
+MediaQueryEvaluator* MediaQueryMatcher::createEvaluator() const
 {
     if (!m_document || !m_document->frame())
         return nullptr;
@@ -78,12 +78,12 @@
     return false;
 }
 
-RawPtr<MediaQueryList> MediaQueryMatcher::matchMedia(const String& query)
+MediaQueryList* MediaQueryMatcher::matchMedia(const String& query)
 {
     if (!m_document)
         return nullptr;
 
-    RawPtr<MediaQuerySet> media = MediaQuerySet::create(query);
+    MediaQuerySet* media = MediaQuerySet::create(query);
     return MediaQueryList::create(m_document, this, media);
 }
 
@@ -101,14 +101,14 @@
     m_mediaLists.remove(query);
 }
 
-void MediaQueryMatcher::addViewportListener(RawPtr<MediaQueryListListener> listener)
+void MediaQueryMatcher::addViewportListener(MediaQueryListListener* listener)
 {
     if (!m_document)
         return;
     m_viewportListeners.add(listener);
 }
 
-void MediaQueryMatcher::removeViewportListener(RawPtr<MediaQueryListListener> listener)
+void MediaQueryMatcher::removeViewportListener(MediaQueryListListener* listener)
 {
     if (!m_document)
         return;
@@ -123,7 +123,7 @@
     HeapVector<Member<MediaQueryListListener>> listenersToNotify;
     for (const auto& list : m_mediaLists) {
         if (list->mediaFeaturesChanged(&listenersToNotify)) {
-            RawPtr<Event> event(MediaQueryListEvent::create(list));
+            Event* event = MediaQueryListEvent::create(list);
             event->setTarget(list);
             m_document->enqueueUniqueAnimationFrameEvent(event);
         }
diff --git a/third_party/WebKit/Source/core/css/MediaQueryMatcher.h b/third_party/WebKit/Source/core/css/MediaQueryMatcher.h
index 76412be..e7eda31 100644
--- a/third_party/WebKit/Source/core/css/MediaQueryMatcher.h
+++ b/third_party/WebKit/Source/core/css/MediaQueryMatcher.h
@@ -41,7 +41,7 @@
 class CORE_EXPORT MediaQueryMatcher final : public GarbageCollectedFinalized<MediaQueryMatcher> {
     WTF_MAKE_NONCOPYABLE(MediaQueryMatcher);
 public:
-    static RawPtr<MediaQueryMatcher> create(Document&);
+    static MediaQueryMatcher* create(Document&);
     ~MediaQueryMatcher();
 
     void documentDetached();
@@ -49,10 +49,10 @@
     void addMediaQueryList(MediaQueryList*);
     void removeMediaQueryList(MediaQueryList*);
 
-    void addViewportListener(RawPtr<MediaQueryListListener>);
-    void removeViewportListener(RawPtr<MediaQueryListListener>);
+    void addViewportListener(MediaQueryListListener*);
+    void removeViewportListener(MediaQueryListListener*);
 
-    RawPtr<MediaQueryList> matchMedia(const String&);
+    MediaQueryList* matchMedia(const String&);
 
     void mediaFeaturesChanged();
     void viewportChanged();
@@ -63,7 +63,7 @@
 private:
     explicit MediaQueryMatcher(Document&);
 
-    RawPtr<MediaQueryEvaluator> createEvaluator() const;
+    MediaQueryEvaluator* createEvaluator() const;
 
     Member<Document> m_document;
     Member<MediaQueryEvaluator> m_evaluator;
diff --git a/third_party/WebKit/Source/core/css/MediaQueryMatcherTest.cpp b/third_party/WebKit/Source/core/css/MediaQueryMatcherTest.cpp
index 8d8c155..b201c81 100644
--- a/third_party/WebKit/Source/core/css/MediaQueryMatcherTest.cpp
+++ b/third_party/WebKit/Source/core/css/MediaQueryMatcherTest.cpp
@@ -14,12 +14,12 @@
 TEST(MediaQueryMatcherTest, LostFrame)
 {
     OwnPtr<DummyPageHolder> pageHolder = DummyPageHolder::create(IntSize(500, 500));
-    RawPtr<MediaQueryMatcher> matcher = MediaQueryMatcher::create(pageHolder->document());
-    RawPtr<MediaQuerySet> querySet = MediaQuerySet::create(MediaTypeNames::all);
-    ASSERT_TRUE(matcher->evaluate(querySet.get()));
+    MediaQueryMatcher* matcher = MediaQueryMatcher::create(pageHolder->document());
+    MediaQuerySet* querySet = MediaQuerySet::create(MediaTypeNames::all);
+    ASSERT_TRUE(matcher->evaluate(querySet));
 
     matcher->documentDetached();
-    ASSERT_FALSE(matcher->evaluate(querySet.get()));
+    ASSERT_FALSE(matcher->evaluate(querySet));
 }
 
 } // namespace blink
diff --git a/third_party/WebKit/Source/core/css/MediaQuerySetTest.cpp b/third_party/WebKit/Source/core/css/MediaQuerySetTest.cpp
index 7ce16e1..6cea8f2 100644
--- a/third_party/WebKit/Source/core/css/MediaQuerySetTest.cpp
+++ b/third_party/WebKit/Source/core/css/MediaQuerySetTest.cpp
@@ -171,8 +171,8 @@
     };
 
     for (unsigned i = 0; testCases[i].input; ++i) {
-        RawPtr<MediaQuerySet> oldParserQuerySet = MediaQuerySet::create(testCases[i].input);
-        RawPtr<MediaQuerySet> threadSafeQuerySet = MediaQuerySet::createOffMainThread(testCases[i].input);
+        MediaQuerySet* oldParserQuerySet = MediaQuerySet::create(testCases[i].input);
+        MediaQuerySet* threadSafeQuerySet = MediaQuerySet::createOffMainThread(testCases[i].input);
         testMediaQuery(testCases[i], *oldParserQuerySet, true);
         testMediaQuery(testCases[i], *threadSafeQuerySet, false);
     }
diff --git a/third_party/WebKit/Source/core/css/MediaValues.cpp b/third_party/WebKit/Source/core/css/MediaValues.cpp
index 91ed0b7..6f7cbc2 100644
--- a/third_party/WebKit/Source/core/css/MediaValues.cpp
+++ b/third_party/WebKit/Source/core/css/MediaValues.cpp
@@ -24,7 +24,7 @@
 
 namespace blink {
 
-RawPtr<MediaValues> MediaValues::createDynamicIfFrameExists(LocalFrame* frame)
+MediaValues* MediaValues::createDynamicIfFrameExists(LocalFrame* frame)
 {
     if (frame)
         return MediaValuesDynamic::create(frame);
diff --git a/third_party/WebKit/Source/core/css/MediaValues.h b/third_party/WebKit/Source/core/css/MediaValues.h
index 90b6bcc..7125b66f 100644
--- a/third_party/WebKit/Source/core/css/MediaValues.h
+++ b/third_party/WebKit/Source/core/css/MediaValues.h
@@ -24,8 +24,8 @@
     virtual ~MediaValues() { }
     DEFINE_INLINE_VIRTUAL_TRACE() { }
 
-    static RawPtr<MediaValues> createDynamicIfFrameExists(LocalFrame*);
-    virtual RawPtr<MediaValues> copy() const = 0;
+    static MediaValues* createDynamicIfFrameExists(LocalFrame*);
+    virtual MediaValues* copy() const = 0;
 
     static bool computeLengthImpl(double value, CSSPrimitiveValue::UnitType, unsigned defaultFontSize, double viewportWidth, double viewportHeight, double& result);
     template<typename T>
diff --git a/third_party/WebKit/Source/core/css/MediaValuesCached.cpp b/third_party/WebKit/Source/core/css/MediaValuesCached.cpp
index b935d766..5879bf1ee7 100644
--- a/third_party/WebKit/Source/core/css/MediaValuesCached.cpp
+++ b/third_party/WebKit/Source/core/css/MediaValuesCached.cpp
@@ -42,12 +42,12 @@
     }
 }
 
-RawPtr<MediaValuesCached> MediaValuesCached::create()
+MediaValuesCached* MediaValuesCached::create()
 {
     return new MediaValuesCached();
 }
 
-RawPtr<MediaValuesCached> MediaValuesCached::create(const MediaValuesCachedData& data)
+MediaValuesCached* MediaValuesCached::create(const MediaValuesCachedData& data)
 {
     return new MediaValuesCached(data);
 }
@@ -61,7 +61,7 @@
 {
 }
 
-RawPtr<MediaValues> MediaValuesCached::copy() const
+MediaValues* MediaValuesCached::copy() const
 {
     return new MediaValuesCached(m_data);
 }
diff --git a/third_party/WebKit/Source/core/css/MediaValuesCached.h b/third_party/WebKit/Source/core/css/MediaValuesCached.h
index 3b21f18..8fddc52 100644
--- a/third_party/WebKit/Source/core/css/MediaValuesCached.h
+++ b/third_party/WebKit/Source/core/css/MediaValuesCached.h
@@ -76,9 +76,9 @@
         }
     };
 
-    static RawPtr<MediaValuesCached> create();
-    static RawPtr<MediaValuesCached> create(const MediaValuesCachedData&);
-    RawPtr<MediaValues> copy() const override;
+    static MediaValuesCached* create();
+    static MediaValuesCached* create(const MediaValuesCachedData&);
+    MediaValues* copy() const override;
     bool computeLength(double value, CSSPrimitiveValue::UnitType, int& result) const override;
     bool computeLength(double value, CSSPrimitiveValue::UnitType, double& result) const override;
 
diff --git a/third_party/WebKit/Source/core/css/MediaValuesDynamic.cpp b/third_party/WebKit/Source/core/css/MediaValuesDynamic.cpp
index c51389b..24f3aec 100644
--- a/third_party/WebKit/Source/core/css/MediaValuesDynamic.cpp
+++ b/third_party/WebKit/Source/core/css/MediaValuesDynamic.cpp
@@ -13,12 +13,12 @@
 
 namespace blink {
 
-RawPtr<MediaValues> MediaValuesDynamic::create(Document& document)
+MediaValues* MediaValuesDynamic::create(Document& document)
 {
     return MediaValuesDynamic::create(frameFrom(document));
 }
 
-RawPtr<MediaValues> MediaValuesDynamic::create(LocalFrame* frame)
+MediaValues* MediaValuesDynamic::create(LocalFrame* frame)
 {
     if (!frame || !frame->view() || !frame->document() || !frame->document()->layoutView())
         return MediaValuesCached::create();
@@ -43,7 +43,7 @@
     ASSERT(m_frame);
 }
 
-RawPtr<MediaValues> MediaValuesDynamic::copy() const
+MediaValues* MediaValuesDynamic::copy() const
 {
     return new MediaValuesDynamic(m_frame, m_viewportDimensionsOverridden, m_viewportWidthOverride, m_viewportHeightOverride);
 }
diff --git a/third_party/WebKit/Source/core/css/MediaValuesDynamic.h b/third_party/WebKit/Source/core/css/MediaValuesDynamic.h
index 945c2c55..476a46f 100644
--- a/third_party/WebKit/Source/core/css/MediaValuesDynamic.h
+++ b/third_party/WebKit/Source/core/css/MediaValuesDynamic.h
@@ -13,9 +13,9 @@
 
 class MediaValuesDynamic final : public MediaValues {
 public:
-    static RawPtr<MediaValues> create(Document&);
-    static RawPtr<MediaValues> create(LocalFrame*);
-    RawPtr<MediaValues> copy() const override;
+    static MediaValues* create(Document&);
+    static MediaValues* create(LocalFrame*);
+    MediaValues* copy() const override;
     bool computeLength(double value, CSSPrimitiveValue::UnitType, int& result) const override;
     bool computeLength(double value, CSSPrimitiveValue::UnitType, double& result) const override;
 
diff --git a/third_party/WebKit/Source/core/css/PropertySetCSSStyleDeclaration.cpp b/third_party/WebKit/Source/core/css/PropertySetCSSStyleDeclaration.cpp
index d135b7b..3ac4257f 100644
--- a/third_party/WebKit/Source/core/css/PropertySetCSSStyleDeclaration.cpp
+++ b/third_party/WebKit/Source/core/css/PropertySetCSSStyleDeclaration.cpp
@@ -270,7 +270,7 @@
     return result;
 }
 
-RawPtr<CSSValue> AbstractPropertySetCSSStyleDeclaration::getPropertyCSSValueInternal(CSSPropertyID propertyID)
+CSSValue* AbstractPropertySetCSSStyleDeclaration::getPropertyCSSValueInternal(CSSPropertyID propertyID)
 {
     return propertySet().getPropertyCSSValue(propertyID);
 }
diff --git a/third_party/WebKit/Source/core/css/PropertySetCSSStyleDeclaration.h b/third_party/WebKit/Source/core/css/PropertySetCSSStyleDeclaration.h
index 7d50cf37..2157d74 100644
--- a/third_party/WebKit/Source/core/css/PropertySetCSSStyleDeclaration.h
+++ b/third_party/WebKit/Source/core/css/PropertySetCSSStyleDeclaration.h
@@ -60,7 +60,7 @@
     void setCSSFloat(const String&, ExceptionState&);
     String cssText() const final;
     void setCSSText(const String&, ExceptionState&) final;
-    RawPtr<CSSValue> getPropertyCSSValueInternal(CSSPropertyID) final;
+    CSSValue* getPropertyCSSValueInternal(CSSPropertyID) final;
     String getPropertyValueInternal(CSSPropertyID) final;
     void setPropertyInternal(CSSPropertyID, const String& customPropertyName, const String& value, bool important, ExceptionState&) final;
 
@@ -92,7 +92,7 @@
 
 class StyleRuleCSSStyleDeclaration : public PropertySetCSSStyleDeclaration {
 public:
-    static RawPtr<StyleRuleCSSStyleDeclaration> create(MutableStylePropertySet& propertySet, CSSRule* parentRule)
+    static StyleRuleCSSStyleDeclaration* create(MutableStylePropertySet& propertySet, CSSRule* parentRule)
     {
         return new StyleRuleCSSStyleDeclaration(propertySet, parentRule);
     }
diff --git a/third_party/WebKit/Source/core/css/RemoteFontFaceSource.cpp b/third_party/WebKit/Source/core/css/RemoteFontFaceSource.cpp
index 764cf173..3d5e63f 100644
--- a/third_party/WebKit/Source/core/css/RemoteFontFaceSource.cpp
+++ b/third_party/WebKit/Source/core/css/RemoteFontFaceSource.cpp
@@ -17,7 +17,7 @@
 
 namespace blink {
 
-RemoteFontFaceSource::RemoteFontFaceSource(RawPtr<FontResource> font, RawPtr<FontLoader> fontLoader, FontDisplay display)
+RemoteFontFaceSource::RemoteFontFaceSource(FontResource* font, FontLoader* fontLoader, FontDisplay display)
     : m_font(font)
     , m_fontLoader(fontLoader)
     , m_display(display)
diff --git a/third_party/WebKit/Source/core/css/RemoteFontFaceSource.h b/third_party/WebKit/Source/core/css/RemoteFontFaceSource.h
index 88f2566..0178073 100644
--- a/third_party/WebKit/Source/core/css/RemoteFontFaceSource.h
+++ b/third_party/WebKit/Source/core/css/RemoteFontFaceSource.h
@@ -27,7 +27,7 @@
 public:
     enum DisplayPeriod { BlockPeriod, SwapPeriod, FailurePeriod };
 
-    explicit RemoteFontFaceSource(RawPtr<FontResource>, RawPtr<FontLoader>, FontDisplay);
+    explicit RemoteFontFaceSource(FontResource*, FontLoader*, FontDisplay);
     ~RemoteFontFaceSource() override;
     void dispose();
 
diff --git a/third_party/WebKit/Source/core/css/RuleFeatureSetTest.cpp b/third_party/WebKit/Source/core/css/RuleFeatureSetTest.cpp
index 7b194f3..c625113 100644
--- a/third_party/WebKit/Source/core/css/RuleFeatureSetTest.cpp
+++ b/third_party/WebKit/Source/core/css/RuleFeatureSetTest.cpp
@@ -28,9 +28,9 @@
     void SetUp()
     {
         m_document = HTMLDocument::create();
-        RawPtr<HTMLHtmlElement> html = HTMLHtmlElement::create(*m_document);
+        HTMLHtmlElement* html = HTMLHtmlElement::create(*m_document);
         html->appendChild(HTMLBodyElement::create(*m_document));
-        m_document->appendChild(html.release());
+        m_document->appendChild(html);
 
         m_document->body()->setInnerHTML("<b><i></i></b>", ASSERT_NO_EXCEPTION);
     }
@@ -39,8 +39,8 @@
     {
         CSSSelectorList selectorList = CSSParser::parseSelector(strictCSSParserContext(), nullptr, selectorText);
 
-        RawPtr<StyleRule> styleRule = StyleRule::create(std::move(selectorList), MutableStylePropertySet::create(HTMLStandardMode));
-        RuleData ruleData(styleRule.get(), 0, 0, RuleHasNoSpecialState);
+        StyleRule* styleRule = StyleRule::create(std::move(selectorList), MutableStylePropertySet::create(HTMLStandardMode));
+        RuleData ruleData(styleRule, 0, 0, RuleHasNoSpecialState);
         return m_ruleFeatureSet.collectFeaturesFromRuleData(ruleData);
     }
 
diff --git a/third_party/WebKit/Source/core/css/RuleSet.cpp b/third_party/WebKit/Source/core/css/RuleSet.cpp
index 87cdaac..6d91eeb 100644
--- a/third_party/WebKit/Source/core/css/RuleSet.cpp
+++ b/third_party/WebKit/Source/core/css/RuleSet.cpp
@@ -312,7 +312,7 @@
 void RuleSet::compactPendingRules(PendingRuleMap& pendingMap, CompactRuleMap& compactMap)
 {
     for (auto& item : pendingMap) {
-        RawPtr<HeapLinkedStack<RuleData>> pendingRules = item.value.release();
+        HeapLinkedStack<RuleData>* pendingRules = item.value.release();
         CompactRuleMap::ValueType* compactRules = compactMap.add(item.key, nullptr).storedValue;
 
         HeapTerminatedArrayBuilder<RuleData> builder(compactRules->value.release());
@@ -329,7 +329,7 @@
 void RuleSet::compactRules()
 {
     ASSERT(m_pendingRules);
-    RawPtr<PendingRuleMaps> pendingRules = m_pendingRules.release();
+    PendingRuleMaps* pendingRules = m_pendingRules.release();
     compactPendingRules(pendingRules->idRules, m_idRules);
     compactPendingRules(pendingRules->classRules, m_classRules);
     compactPendingRules(pendingRules->tagRules, m_tagRules);
diff --git a/third_party/WebKit/Source/core/css/RuleSet.h b/third_party/WebKit/Source/core/css/RuleSet.h
index 6690dcd8..61342055 100644
--- a/third_party/WebKit/Source/core/css/RuleSet.h
+++ b/third_party/WebKit/Source/core/css/RuleSet.h
@@ -122,7 +122,7 @@
 class CORE_EXPORT RuleSet : public GarbageCollectedFinalized<RuleSet> {
     WTF_MAKE_NONCOPYABLE(RuleSet);
 public:
-    static RawPtr<RuleSet> create() { return new RuleSet; }
+    static RuleSet* create() { return new RuleSet; }
 
     void addRulesFromSheet(StyleSheetContents*, const MediaQueryEvaluator&, AddRuleFlags = RuleHasNoSpecialState);
     void addStyleRule(StyleRule*, AddRuleFlags);
@@ -187,7 +187,7 @@
 
     class PendingRuleMaps : public GarbageCollected<PendingRuleMaps> {
     public:
-        static RawPtr<PendingRuleMaps> create() { return new PendingRuleMaps; }
+        static PendingRuleMaps* create() { return new PendingRuleMaps; }
 
         PendingRuleMap idRules;
         PendingRuleMap classRules;
diff --git a/third_party/WebKit/Source/core/css/StyleMedia.cpp b/third_party/WebKit/Source/core/css/StyleMedia.cpp
index 9c1c562..9fdbe32 100644
--- a/third_party/WebKit/Source/core/css/StyleMedia.cpp
+++ b/third_party/WebKit/Source/core/css/StyleMedia.cpp
@@ -58,12 +58,12 @@
     if (!documentElement)
         return false;
 
-    RawPtr<MediaQuerySet> media = MediaQuerySet::create();
+    MediaQuerySet* media = MediaQuerySet::create();
     if (!media->set(query))
         return false;
 
     MediaQueryEvaluator screenEval(m_frame);
-    return screenEval.eval(media.get());
+    return screenEval.eval(media);
 }
 
 DEFINE_TRACE(StyleMedia)
diff --git a/third_party/WebKit/Source/core/css/StyleMedia.h b/third_party/WebKit/Source/core/css/StyleMedia.h
index 7c16c64..0b4e461 100644
--- a/third_party/WebKit/Source/core/css/StyleMedia.h
+++ b/third_party/WebKit/Source/core/css/StyleMedia.h
@@ -41,7 +41,7 @@
     DEFINE_WRAPPERTYPEINFO();
     USING_GARBAGE_COLLECTED_MIXIN(StyleMedia);
 public:
-    static RawPtr<StyleMedia> create(LocalFrame* frame) { return new StyleMedia(frame);}
+    static StyleMedia* create(LocalFrame* frame) { return new StyleMedia(frame);}
 
     AtomicString type() const;
     bool matchMedium(const String&) const;
diff --git a/third_party/WebKit/Source/core/css/StylePropertySet.cpp b/third_party/WebKit/Source/core/css/StylePropertySet.cpp
index 09a1e44..cb98e5ff 100644
--- a/third_party/WebKit/Source/core/css/StylePropertySet.cpp
+++ b/third_party/WebKit/Source/core/css/StylePropertySet.cpp
@@ -45,14 +45,14 @@
     return sizeof(ImmutableStylePropertySet) - sizeof(void*) + sizeof(Member<CSSValue>) * count + sizeof(StylePropertyMetadata) * count;
 }
 
-RawPtr<ImmutableStylePropertySet> ImmutableStylePropertySet::create(const CSSProperty* properties, unsigned count, CSSParserMode cssParserMode)
+ImmutableStylePropertySet* ImmutableStylePropertySet::create(const CSSProperty* properties, unsigned count, CSSParserMode cssParserMode)
 {
     ASSERT(count <= MaxArraySize);
     void* slot = Heap::allocate<StylePropertySet>(sizeForImmutableStylePropertySetWithPropertyCount(count));
     return new (slot) ImmutableStylePropertySet(properties, count, cssParserMode);
 }
 
-RawPtr<ImmutableStylePropertySet> StylePropertySet::immutableCopyIfNeeded() const
+ImmutableStylePropertySet* StylePropertySet::immutableCopyIfNeeded() const
 {
     if (!isMutable())
         return toImmutableStylePropertySet(const_cast<StylePropertySet*>(this));
@@ -175,7 +175,7 @@
 template<typename T>
 String StylePropertySet::getPropertyValue(T property) const
 {
-    RawPtr<CSSValue> value = getPropertyCSSValue(property);
+    CSSValue* value = getPropertyCSSValue(property);
     if (value)
         return value->cssText();
     return serializeShorthand(*this, property);
@@ -184,15 +184,15 @@
 template CORE_EXPORT String StylePropertySet::getPropertyValue<AtomicString>(AtomicString) const;
 
 template<typename T>
-RawPtr<CSSValue> StylePropertySet::getPropertyCSSValue(T property) const
+CSSValue* StylePropertySet::getPropertyCSSValue(T property) const
 {
     int foundPropertyIndex = findPropertyIndex(property);
     if (foundPropertyIndex == -1)
         return nullptr;
     return propertyAt(foundPropertyIndex).value();
 }
-template CORE_EXPORT RawPtr<CSSValue> StylePropertySet::getPropertyCSSValue<CSSPropertyID>(CSSPropertyID) const;
-template CORE_EXPORT RawPtr<CSSValue> StylePropertySet::getPropertyCSSValue<AtomicString>(AtomicString) const;
+template CORE_EXPORT CSSValue* StylePropertySet::getPropertyCSSValue<CSSPropertyID>(CSSPropertyID) const;
+template CORE_EXPORT CSSValue* StylePropertySet::getPropertyCSSValue<AtomicString>(AtomicString) const;
 
 DEFINE_TRACE(StylePropertySet)
 {
@@ -320,17 +320,16 @@
     return CSSParser::parseValueForCustomProperty(this, customPropertyName, value, important, contextStyleSheet);
 }
 
-void MutableStylePropertySet::setProperty(CSSPropertyID propertyID, RawPtr<CSSValue> prpValue, bool important)
+void MutableStylePropertySet::setProperty(CSSPropertyID propertyID, CSSValue* value, bool important)
 {
     StylePropertyShorthand shorthand = shorthandForProperty(propertyID);
     if (!shorthand.length()) {
-        setProperty(CSSProperty(propertyID, prpValue, important));
+        setProperty(CSSProperty(propertyID, value, important));
         return;
     }
 
     removePropertiesInSet(shorthand.properties(), shorthand.length());
 
-    RawPtr<CSSValue> value = prpValue;
     for (unsigned i = 0; i < shorthand.length(); ++i)
         m_propertyVector.append(CSSProperty(shorthand.properties()[i], value, important));
 }
@@ -505,19 +504,19 @@
         removeProperty(propertiesToRemove[i]);
 }
 
-RawPtr<MutableStylePropertySet> StylePropertySet::mutableCopy() const
+MutableStylePropertySet* StylePropertySet::mutableCopy() const
 {
     return new MutableStylePropertySet(*this);
 }
 
-RawPtr<MutableStylePropertySet> StylePropertySet::copyPropertiesInSet(const Vector<CSSPropertyID>& properties) const
+MutableStylePropertySet* StylePropertySet::copyPropertiesInSet(const Vector<CSSPropertyID>& properties) const
 {
     HeapVector<CSSProperty, 256> list;
     list.reserveInitialCapacity(properties.size());
     for (unsigned i = 0; i < properties.size(); ++i) {
-        RawPtr<CSSValue> value = getPropertyCSSValue(properties[i]);
+        CSSValue* value = getPropertyCSSValue(properties[i]);
         if (value)
-            list.append(CSSProperty(properties[i], value.release(), false));
+            list.append(CSSProperty(properties[i], value, false));
     }
     return MutableStylePropertySet::create(list.data(), list.size());
 }
@@ -578,12 +577,12 @@
 }
 #endif
 
-RawPtr<MutableStylePropertySet> MutableStylePropertySet::create(CSSParserMode cssParserMode)
+MutableStylePropertySet* MutableStylePropertySet::create(CSSParserMode cssParserMode)
 {
     return new MutableStylePropertySet(cssParserMode);
 }
 
-RawPtr<MutableStylePropertySet> MutableStylePropertySet::create(const CSSProperty* properties, unsigned count)
+MutableStylePropertySet* MutableStylePropertySet::create(const CSSProperty* properties, unsigned count)
 {
     return new MutableStylePropertySet(properties, count);
 }
diff --git a/third_party/WebKit/Source/core/css/StylePropertySet.h b/third_party/WebKit/Source/core/css/StylePropertySet.h
index 2245a4a9..6fd4c60c 100644
--- a/third_party/WebKit/Source/core/css/StylePropertySet.h
+++ b/third_party/WebKit/Source/core/css/StylePropertySet.h
@@ -98,7 +98,7 @@
     bool hasProperty(CSSPropertyID property) const { return findPropertyIndex(property) != -1; }
 
     template<typename T> // CSSPropertyID or AtomicString
-    RawPtr<CSSValue> getPropertyCSSValue(T property) const;
+    CSSValue* getPropertyCSSValue(T property) const;
 
     template<typename T> // CSSPropertyID or AtomicString
     String getPropertyValue(T property) const;
@@ -114,10 +114,10 @@
 
     CSSParserMode cssParserMode() const { return static_cast<CSSParserMode>(m_cssParserMode); }
 
-    RawPtr<MutableStylePropertySet> mutableCopy() const;
-    RawPtr<ImmutableStylePropertySet> immutableCopyIfNeeded() const;
+    MutableStylePropertySet* mutableCopy() const;
+    ImmutableStylePropertySet* immutableCopyIfNeeded() const;
 
-    RawPtr<MutableStylePropertySet> copyPropertiesInSet(const Vector<CSSPropertyID>&) const;
+    MutableStylePropertySet* copyPropertiesInSet(const Vector<CSSPropertyID>&) const;
 
     String asText() const;
 
@@ -162,7 +162,7 @@
 class CORE_EXPORT ImmutableStylePropertySet : public StylePropertySet {
 public:
     ~ImmutableStylePropertySet();
-    static RawPtr<ImmutableStylePropertySet> create(const CSSProperty* properties, unsigned count, CSSParserMode);
+    static ImmutableStylePropertySet* create(const CSSProperty* properties, unsigned count, CSSParserMode);
 
     unsigned propertyCount() const { return m_arraySize; }
 
@@ -200,8 +200,8 @@
 class CORE_EXPORT MutableStylePropertySet : public StylePropertySet {
 public:
     ~MutableStylePropertySet() { }
-    static RawPtr<MutableStylePropertySet> create(CSSParserMode);
-    static RawPtr<MutableStylePropertySet> create(const CSSProperty* properties, unsigned count);
+    static MutableStylePropertySet* create(CSSParserMode);
+    static MutableStylePropertySet* create(const CSSProperty* properties, unsigned count);
 
     unsigned propertyCount() const { return m_propertyVector.size(); }
 
@@ -212,7 +212,7 @@
     // These expand shorthand properties into multiple properties.
     bool setProperty(CSSPropertyID unresolvedProperty, const String& value, bool important = false, StyleSheetContents* contextStyleSheet = 0);
     bool setProperty(const AtomicString& customPropertyName, const String& value, bool important = false, StyleSheetContents* contextStyleSheet = 0);
-    void setProperty(CSSPropertyID, RawPtr<CSSValue>, bool important = false);
+    void setProperty(CSSPropertyID, CSSValue*, bool important = false);
 
     // These do not. FIXME: This is too messy, we can do better.
     bool setProperty(CSSPropertyID, CSSValueID identifier, bool important = false);
@@ -255,11 +255,6 @@
 
 DEFINE_TYPE_CASTS(MutableStylePropertySet, StylePropertySet, set, set->isMutable(), set.isMutable());
 
-inline MutableStylePropertySet* toMutableStylePropertySet(const RawPtr<StylePropertySet>& set)
-{
-    return toMutableStylePropertySet(set.get());
-}
-
 inline MutableStylePropertySet* toMutableStylePropertySet(const Persistent<StylePropertySet>& set)
 {
     return toMutableStylePropertySet(set.get());
diff --git a/third_party/WebKit/Source/core/css/StyleRule.cpp b/third_party/WebKit/Source/core/css/StyleRule.cpp
index e353850..d1d8511 100644
--- a/third_party/WebKit/Source/core/css/StyleRule.cpp
+++ b/third_party/WebKit/Source/core/css/StyleRule.cpp
@@ -42,12 +42,12 @@
 
 static_assert(sizeof(StyleRuleBase) <= sizeof(SameSizeAsStyleRuleBase), "StyleRuleBase should stay small");
 
-RawPtr<CSSRule> StyleRuleBase::createCSSOMWrapper(CSSStyleSheet* parentSheet) const
+CSSRule* StyleRuleBase::createCSSOMWrapper(CSSStyleSheet* parentSheet) const
 {
     return createCSSOMWrapper(parentSheet, 0);
 }
 
-RawPtr<CSSRule> StyleRuleBase::createCSSOMWrapper(CSSRule* parentRule) const
+CSSRule* StyleRuleBase::createCSSOMWrapper(CSSRule* parentRule) const
 {
     return createCSSOMWrapper(0, parentRule);
 }
@@ -172,7 +172,7 @@
     ASSERT_NOT_REACHED();
 }
 
-RawPtr<StyleRuleBase> StyleRuleBase::copy() const
+StyleRuleBase* StyleRuleBase::copy() const
 {
     switch (type()) {
     case Style:
@@ -203,9 +203,9 @@
     return nullptr;
 }
 
-RawPtr<CSSRule> StyleRuleBase::createCSSOMWrapper(CSSStyleSheet* parentSheet, CSSRule* parentRule) const
+CSSRule* StyleRuleBase::createCSSOMWrapper(CSSStyleSheet* parentSheet, CSSRule* parentRule) const
 {
-    RawPtr<CSSRule> rule = nullptr;
+    CSSRule* rule = nullptr;
     StyleRuleBase* self = const_cast<StyleRuleBase*>(this);
     switch (type()) {
     case Style:
@@ -242,7 +242,7 @@
     }
     if (parentRule)
         rule->setParentRule(parentRule);
-    return rule.release();
+    return rule;
 }
 
 unsigned StyleRule::averageSizeInBytes()
@@ -250,7 +250,7 @@
     return sizeof(StyleRule) + sizeof(CSSSelector) + StylePropertySet::averageSizeInBytes();
 }
 
-StyleRule::StyleRule(CSSSelectorList selectorList, RawPtr<StylePropertySet> properties)
+StyleRule::StyleRule(CSSSelectorList selectorList, StylePropertySet* properties)
     : StyleRuleBase(Style)
     , m_properties(properties)
 {
@@ -281,7 +281,7 @@
     StyleRuleBase::traceAfterDispatch(visitor);
 }
 
-StyleRulePage::StyleRulePage(CSSSelectorList selectorList, RawPtr<StylePropertySet> properties)
+StyleRulePage::StyleRulePage(CSSSelectorList selectorList, StylePropertySet* properties)
     : StyleRuleBase(Page)
     , m_properties(properties)
     , m_selectorList(std::move(selectorList))
@@ -312,7 +312,7 @@
     StyleRuleBase::traceAfterDispatch(visitor);
 }
 
-StyleRuleFontFace::StyleRuleFontFace(RawPtr<StylePropertySet> properties)
+StyleRuleFontFace::StyleRuleFontFace(StylePropertySet* properties)
     : StyleRuleBase(FontFace)
     , m_properties(properties)
 {
@@ -355,7 +355,7 @@
         m_childRules[i] = o.m_childRules[i]->copy();
 }
 
-void StyleRuleGroup::wrapperInsertRule(unsigned index, RawPtr<StyleRuleBase> rule)
+void StyleRuleGroup::wrapperInsertRule(unsigned index, StyleRuleBase* rule)
 {
     m_childRules.insert(index, rule);
 }
@@ -371,7 +371,7 @@
     StyleRuleBase::traceAfterDispatch(visitor);
 }
 
-StyleRuleMedia::StyleRuleMedia(RawPtr<MediaQuerySet> media, HeapVector<Member<StyleRuleBase>>& adoptRules)
+StyleRuleMedia::StyleRuleMedia(MediaQuerySet* media, HeapVector<Member<StyleRuleBase>>& adoptRules)
     : StyleRuleGroup(Media, adoptRules)
     , m_mediaQueries(media)
 {
@@ -404,7 +404,7 @@
 {
 }
 
-StyleRuleViewport::StyleRuleViewport(RawPtr<StylePropertySet> properties)
+StyleRuleViewport::StyleRuleViewport(StylePropertySet* properties)
     : StyleRuleBase(Viewport)
     , m_properties(properties)
 {
diff --git a/third_party/WebKit/Source/core/css/StyleRule.h b/third_party/WebKit/Source/core/css/StyleRule.h
index 7b034bd..f53a3ef 100644
--- a/third_party/WebKit/Source/core/css/StyleRule.h
+++ b/third_party/WebKit/Source/core/css/StyleRule.h
@@ -64,7 +64,7 @@
     bool isViewportRule() const { return type() == Viewport; }
     bool isImportRule() const { return type() == Import; }
 
-    RawPtr<StyleRuleBase> copy() const;
+    StyleRuleBase* copy() const;
 
 #if !ENABLE(OILPAN)
     void deref()
@@ -75,8 +75,8 @@
 #endif // !ENABLE(OILPAN)
 
     // FIXME: There shouldn't be any need for the null parent version.
-    RawPtr<CSSRule> createCSSOMWrapper(CSSStyleSheet* parentSheet = 0) const;
-    RawPtr<CSSRule> createCSSOMWrapper(CSSRule* parentRule) const;
+    CSSRule* createCSSOMWrapper(CSSStyleSheet* parentSheet = 0) const;
+    CSSRule* createCSSOMWrapper(CSSRule* parentRule) const;
 
     DECLARE_TRACE();
     DEFINE_INLINE_TRACE_AFTER_DISPATCH() { }
@@ -95,7 +95,7 @@
 private:
     void destroy();
 
-    RawPtr<CSSRule> createCSSOMWrapper(CSSStyleSheet* parentSheet, CSSRule* parentRule) const;
+    CSSRule* createCSSOMWrapper(CSSStyleSheet* parentSheet, CSSRule* parentRule) const;
 
     unsigned m_type : 5;
 };
@@ -103,7 +103,7 @@
 class CORE_EXPORT StyleRule : public StyleRuleBase {
 public:
     // Adopts the selector list
-    static RawPtr<StyleRule> create(CSSSelectorList selectorList, RawPtr<StylePropertySet> properties)
+    static StyleRule* create(CSSSelectorList selectorList, StylePropertySet* properties)
     {
         return new StyleRule(std::move(selectorList), properties);
     }
@@ -116,14 +116,14 @@
 
     void wrapperAdoptSelectorList(CSSSelectorList selectors) { m_selectorList = std::move(selectors); }
 
-    RawPtr<StyleRule> copy() const { return new StyleRule(*this); }
+    StyleRule* copy() const { return new StyleRule(*this); }
 
     static unsigned averageSizeInBytes();
 
     DECLARE_TRACE_AFTER_DISPATCH();
 
 private:
-    StyleRule(CSSSelectorList, RawPtr<StylePropertySet>);
+    StyleRule(CSSSelectorList, StylePropertySet*);
     StyleRule(const StyleRule&);
 
     Member<StylePropertySet> m_properties; // Cannot be null.
@@ -132,7 +132,7 @@
 
 class StyleRuleFontFace : public StyleRuleBase {
 public:
-    static RawPtr<StyleRuleFontFace> create(RawPtr<StylePropertySet> properties)
+    static StyleRuleFontFace* create(StylePropertySet* properties)
     {
         return new StyleRuleFontFace(properties);
     }
@@ -142,12 +142,12 @@
     const StylePropertySet& properties() const { return *m_properties; }
     MutableStylePropertySet& mutableProperties();
 
-    RawPtr<StyleRuleFontFace> copy() const { return new StyleRuleFontFace(*this); }
+    StyleRuleFontFace* copy() const { return new StyleRuleFontFace(*this); }
 
     DECLARE_TRACE_AFTER_DISPATCH();
 
 private:
-    StyleRuleFontFace(RawPtr<StylePropertySet>);
+    StyleRuleFontFace(StylePropertySet*);
     StyleRuleFontFace(const StyleRuleFontFace&);
 
     Member<StylePropertySet> m_properties; // Cannot be null.
@@ -156,7 +156,7 @@
 class StyleRulePage : public StyleRuleBase {
 public:
     // Adopts the selector list
-    static RawPtr<StyleRulePage> create(CSSSelectorList selectorList, RawPtr<StylePropertySet> properties)
+    static StyleRulePage* create(CSSSelectorList selectorList, StylePropertySet* properties)
     {
         return new StyleRulePage(std::move(selectorList), properties);
     }
@@ -169,12 +169,12 @@
 
     void wrapperAdoptSelectorList(CSSSelectorList selectors) { m_selectorList = std::move(selectors); }
 
-    RawPtr<StyleRulePage> copy() const { return new StyleRulePage(*this); }
+    StyleRulePage* copy() const { return new StyleRulePage(*this); }
 
     DECLARE_TRACE_AFTER_DISPATCH();
 
 private:
-    StyleRulePage(CSSSelectorList, RawPtr<StylePropertySet>);
+    StyleRulePage(CSSSelectorList, StylePropertySet*);
     StyleRulePage(const StyleRulePage&);
 
     Member<StylePropertySet> m_properties; // Cannot be null.
@@ -185,7 +185,7 @@
 public:
     const HeapVector<Member<StyleRuleBase>>& childRules() const { return m_childRules; }
 
-    void wrapperInsertRule(unsigned, RawPtr<StyleRuleBase>);
+    void wrapperInsertRule(unsigned, StyleRuleBase*);
     void wrapperRemoveRule(unsigned);
 
     DECLARE_TRACE_AFTER_DISPATCH();
@@ -200,19 +200,19 @@
 
 class StyleRuleMedia : public StyleRuleGroup {
 public:
-    static RawPtr<StyleRuleMedia> create(RawPtr<MediaQuerySet> media, HeapVector<Member<StyleRuleBase>>& adoptRules)
+    static StyleRuleMedia* create(MediaQuerySet* media, HeapVector<Member<StyleRuleBase>>& adoptRules)
     {
         return new StyleRuleMedia(media, adoptRules);
     }
 
     MediaQuerySet* mediaQueries() const { return m_mediaQueries.get(); }
 
-    RawPtr<StyleRuleMedia> copy() const { return new StyleRuleMedia(*this); }
+    StyleRuleMedia* copy() const { return new StyleRuleMedia(*this); }
 
     DECLARE_TRACE_AFTER_DISPATCH();
 
 private:
-    StyleRuleMedia(RawPtr<MediaQuerySet>, HeapVector<Member<StyleRuleBase>>& adoptRules);
+    StyleRuleMedia(MediaQuerySet*, HeapVector<Member<StyleRuleBase>>& adoptRules);
     StyleRuleMedia(const StyleRuleMedia&);
 
     Member<MediaQuerySet> m_mediaQueries;
@@ -220,14 +220,14 @@
 
 class StyleRuleSupports : public StyleRuleGroup {
 public:
-    static RawPtr<StyleRuleSupports> create(const String& conditionText, bool conditionIsSupported, HeapVector<Member<StyleRuleBase>>& adoptRules)
+    static StyleRuleSupports* create(const String& conditionText, bool conditionIsSupported, HeapVector<Member<StyleRuleBase>>& adoptRules)
     {
         return new StyleRuleSupports(conditionText, conditionIsSupported, adoptRules);
     }
 
     String conditionText() const { return m_conditionText; }
     bool conditionIsSupported() const { return m_conditionIsSupported; }
-    RawPtr<StyleRuleSupports> copy() const { return new StyleRuleSupports(*this); }
+    StyleRuleSupports* copy() const { return new StyleRuleSupports(*this); }
 
     DEFINE_INLINE_TRACE_AFTER_DISPATCH() { StyleRuleGroup::traceAfterDispatch(visitor); }
 
@@ -241,7 +241,7 @@
 
 class StyleRuleViewport : public StyleRuleBase {
 public:
-    static RawPtr<StyleRuleViewport> create(RawPtr<StylePropertySet> properties)
+    static StyleRuleViewport* create(StylePropertySet* properties)
     {
         return new StyleRuleViewport(properties);
     }
@@ -251,12 +251,12 @@
     const StylePropertySet& properties() const { return *m_properties; }
     MutableStylePropertySet& mutableProperties();
 
-    RawPtr<StyleRuleViewport> copy() const { return new StyleRuleViewport(*this); }
+    StyleRuleViewport* copy() const { return new StyleRuleViewport(*this); }
 
     DECLARE_TRACE_AFTER_DISPATCH();
 
 private:
-    StyleRuleViewport(RawPtr<StylePropertySet>);
+    StyleRuleViewport(StylePropertySet*);
     StyleRuleViewport(const StyleRuleViewport&);
 
     Member<StylePropertySet> m_properties; // Cannot be null
@@ -265,7 +265,7 @@
 // This should only be used within the CSS Parser
 class StyleRuleCharset : public StyleRuleBase {
 public:
-    static RawPtr<StyleRuleCharset> create() { return new StyleRuleCharset(); }
+    static StyleRuleCharset* create() { return new StyleRuleCharset(); }
     DEFINE_INLINE_TRACE_AFTER_DISPATCH() { StyleRuleBase::traceAfterDispatch(visitor); }
 
 private:
diff --git a/third_party/WebKit/Source/core/css/StyleRuleImport.cpp b/third_party/WebKit/Source/core/css/StyleRuleImport.cpp
index b5cec76..ffbbd7f 100644
--- a/third_party/WebKit/Source/core/css/StyleRuleImport.cpp
+++ b/third_party/WebKit/Source/core/css/StyleRuleImport.cpp
@@ -30,12 +30,12 @@
 
 namespace blink {
 
-RawPtr<StyleRuleImport> StyleRuleImport::create(const String& href, RawPtr<MediaQuerySet> media)
+StyleRuleImport* StyleRuleImport::create(const String& href, MediaQuerySet* media)
 {
     return new StyleRuleImport(href, media);
 }
 
-StyleRuleImport::StyleRuleImport(const String& href, RawPtr<MediaQuerySet> media)
+StyleRuleImport::StyleRuleImport(const String& href, MediaQuerySet* media)
     : StyleRuleBase(Import)
     , m_parentStyleSheet(nullptr)
     , m_styleSheetClient(this)
diff --git a/third_party/WebKit/Source/core/css/StyleRuleImport.h b/third_party/WebKit/Source/core/css/StyleRuleImport.h
index 627a6076..705acf8 100644
--- a/third_party/WebKit/Source/core/css/StyleRuleImport.h
+++ b/third_party/WebKit/Source/core/css/StyleRuleImport.h
@@ -35,7 +35,7 @@
 class StyleRuleImport : public StyleRuleBase {
     USING_PRE_FINALIZER(StyleRuleImport, dispose);
 public:
-    static RawPtr<StyleRuleImport> create(const String& href, RawPtr<MediaQuerySet>);
+    static StyleRuleImport* create(const String& href, MediaQuerySet*);
 
     ~StyleRuleImport();
 
@@ -80,7 +80,7 @@
     void setCSSStyleSheet(const String& href, const KURL& baseURL, const String& charset, const CSSStyleSheetResource*);
     friend class ImportedStyleSheetClient;
 
-    StyleRuleImport(const String& href, RawPtr<MediaQuerySet>);
+    StyleRuleImport(const String& href, MediaQuerySet*);
 
     void dispose();
 
diff --git a/third_party/WebKit/Source/core/css/StyleRuleKeyframe.cpp b/third_party/WebKit/Source/core/css/StyleRuleKeyframe.cpp
index 482ef97..d8b970b 100644
--- a/third_party/WebKit/Source/core/css/StyleRuleKeyframe.cpp
+++ b/third_party/WebKit/Source/core/css/StyleRuleKeyframe.cpp
@@ -10,7 +10,7 @@
 
 namespace blink {
 
-StyleRuleKeyframe::StyleRuleKeyframe(PassOwnPtr<Vector<double>> keys, RawPtr<StylePropertySet> properties)
+StyleRuleKeyframe::StyleRuleKeyframe(PassOwnPtr<Vector<double>> keys, StylePropertySet* properties)
 : StyleRuleBase(Keyframe)
 , m_properties(properties)
 , m_keys(*keys)
diff --git a/third_party/WebKit/Source/core/css/StyleRuleKeyframe.h b/third_party/WebKit/Source/core/css/StyleRuleKeyframe.h
index 40a37f84..0a68c88 100644
--- a/third_party/WebKit/Source/core/css/StyleRuleKeyframe.h
+++ b/third_party/WebKit/Source/core/css/StyleRuleKeyframe.h
@@ -14,7 +14,7 @@
 
 class StyleRuleKeyframe final : public StyleRuleBase {
 public:
-    static RawPtr<StyleRuleKeyframe> create(PassOwnPtr<Vector<double>> keys, RawPtr<StylePropertySet> properties)
+    static StyleRuleKeyframe* create(PassOwnPtr<Vector<double>> keys, StylePropertySet* properties)
     {
         return new StyleRuleKeyframe(keys, properties);
     }
@@ -34,7 +34,7 @@
     DECLARE_TRACE_AFTER_DISPATCH();
 
 private:
-    StyleRuleKeyframe(PassOwnPtr<Vector<double>>, RawPtr<StylePropertySet>);
+    StyleRuleKeyframe(PassOwnPtr<Vector<double>>, StylePropertySet*);
 
     Member<StylePropertySet> m_properties;
     Vector<double> m_keys;
diff --git a/third_party/WebKit/Source/core/css/StyleRuleNamespace.h b/third_party/WebKit/Source/core/css/StyleRuleNamespace.h
index cd22af5..13655ff8 100644
--- a/third_party/WebKit/Source/core/css/StyleRuleNamespace.h
+++ b/third_party/WebKit/Source/core/css/StyleRuleNamespace.h
@@ -13,7 +13,7 @@
 // the parser to pass to a stylesheet
 class StyleRuleNamespace final : public StyleRuleBase {
 public:
-    static RawPtr<StyleRuleNamespace> create(AtomicString prefix, AtomicString uri)
+    static StyleRuleNamespace* create(AtomicString prefix, AtomicString uri)
     {
         return new StyleRuleNamespace(prefix, uri);
     }
diff --git a/third_party/WebKit/Source/core/css/StyleSheetContents.cpp b/third_party/WebKit/Source/core/css/StyleSheetContents.cpp
index 7c7dd2e8..a23a491 100644
--- a/third_party/WebKit/Source/core/css/StyleSheetContents.cpp
+++ b/third_party/WebKit/Source/core/css/StyleSheetContents.cpp
@@ -142,12 +142,12 @@
     return true;
 }
 
-void StyleSheetContents::parserAppendRule(RawPtr<StyleRuleBase> rule)
+void StyleSheetContents::parserAppendRule(StyleRuleBase* rule)
 {
     if (rule->isImportRule()) {
         // Parser enforces that @import rules come before anything else
         ASSERT(m_childRules.isEmpty());
-        StyleRuleImport* importRule = toStyleRuleImport(rule.get());
+        StyleRuleImport* importRule = toStyleRuleImport(rule);
         if (importRule->mediaQueries())
             setHasMediaQueries();
         m_importRules.append(importRule);
@@ -212,7 +212,7 @@
     m_childRules.clear();
 }
 
-bool StyleSheetContents::wrapperInsertRule(RawPtr<StyleRuleBase> rule, unsigned index)
+bool StyleSheetContents::wrapperInsertRule(StyleRuleBase* rule, unsigned index)
 {
     ASSERT(m_isMutable);
     ASSERT_WITH_SECURITY_IMPLICATION(index <= ruleCount());
@@ -222,7 +222,7 @@
         if (!rule->isImportRule())
             return false;
 
-        StyleRuleImport* importRule = toStyleRuleImport(rule.get());
+        StyleRuleImport* importRule = toStyleRuleImport(rule);
         if (importRule->mediaQueries())
             setHasMediaQueries();
 
@@ -246,7 +246,7 @@
         if (!m_childRules.isEmpty())
             return false;
 
-        StyleRuleNamespace* namespaceRule = toStyleRuleNamespace(rule.get());
+        StyleRuleNamespace* namespaceRule = toStyleRuleNamespace(rule);
         m_namespaceRules.insert(index, namespaceRule);
         // For now to be compatible with IE and Firefox if namespace rule with same prefix is added
         // irrespective of adding the rule at any index, last added rule's value is considered.
@@ -381,11 +381,6 @@
     if (isLoading())
         return;
 
-    // Avoid |this| being deleted by scripts that run via
-    // ScriptableDocumentParser::executeScriptsWaitingForResources().
-    // See https://bugs.webkit.org/show_bug.cgi?id=95106
-    RawPtr<StyleSheetContents> protect(this);
-
     StyleSheetContents* parentSheet = parentStyleSheet();
     if (parentSheet) {
         parentSheet->checkLoaded();
@@ -412,7 +407,7 @@
             continue;
 
         // sheetLoaded might be invoked after its owner node is removed from document.
-        if (RawPtr<Node> ownerNode = loadingClients[i]->ownerNode()) {
+        if (Node* ownerNode = loadingClients[i]->ownerNode()) {
             if (loadingClients[i]->sheetLoaded())
                 ownerNode->notifyLoadedSheetAndAllCriticalSubresources(m_didLoadErrorOccur ? Node::ErrorOccurredLoadingSubresource : Node::NoErrorLoadingSubresource);
         }
diff --git a/third_party/WebKit/Source/core/css/StyleSheetContents.h b/third_party/WebKit/Source/core/css/StyleSheetContents.h
index 033fa055..b98b623 100644
--- a/third_party/WebKit/Source/core/css/StyleSheetContents.h
+++ b/third_party/WebKit/Source/core/css/StyleSheetContents.h
@@ -48,15 +48,15 @@
 
 class CORE_EXPORT StyleSheetContents : public GarbageCollectedFinalized<StyleSheetContents> {
 public:
-    static RawPtr<StyleSheetContents> create(const CSSParserContext& context)
+    static StyleSheetContents* create(const CSSParserContext& context)
     {
         return new StyleSheetContents(0, String(), context);
     }
-    static RawPtr<StyleSheetContents> create(const String& originalURL, const CSSParserContext& context)
+    static StyleSheetContents* create(const String& originalURL, const CSSParserContext& context)
     {
         return new StyleSheetContents(0, originalURL, context);
     }
-    static RawPtr<StyleSheetContents> create(StyleRuleImport* ownerRule, const String& originalURL, const CSSParserContext& context)
+    static StyleSheetContents* create(StyleRuleImport* ownerRule, const String& originalURL, const CSSParserContext& context)
     {
         return new StyleSheetContents(ownerRule, originalURL, context);
     }
@@ -97,7 +97,7 @@
     void findFontFaceRules(HeapVector<Member<const StyleRuleFontFace>>& fontFaceRules);
 
     void parserAddNamespace(const AtomicString& prefix, const AtomicString& uri);
-    void parserAppendRule(RawPtr<StyleRuleBase>);
+    void parserAppendRule(StyleRuleBase*);
 
     void clearRules();
 
@@ -123,10 +123,10 @@
 
     unsigned estimatedSizeInBytes() const;
 
-    bool wrapperInsertRule(RawPtr<StyleRuleBase>, unsigned index);
+    bool wrapperInsertRule(StyleRuleBase*, unsigned index);
     bool wrapperDeleteRule(unsigned index);
 
-    RawPtr<StyleSheetContents> copy() const
+    StyleSheetContents* copy() const
     {
         return new StyleSheetContents(*this);
     }
diff --git a/third_party/WebKit/Source/core/css/StyleSheetContentsTest.cpp b/third_party/WebKit/Source/core/css/StyleSheetContentsTest.cpp
index e3d768b..b8028f2b 100644
--- a/third_party/WebKit/Source/core/css/StyleSheetContentsTest.cpp
+++ b/third_party/WebKit/Source/core/css/StyleSheetContentsTest.cpp
@@ -14,16 +14,16 @@
 {
     CSSParserContext context(HTMLStandardMode, nullptr);
 
-    RawPtr<StyleSheetContents> styleSheet = StyleSheetContents::create(context);
+    StyleSheetContents* styleSheet = StyleSheetContents::create(context);
     styleSheet->parseString("@namespace ns url(test);");
     EXPECT_EQ(1U, styleSheet->ruleCount());
 
     styleSheet->setMutable();
-    styleSheet->wrapperInsertRule(CSSParser::parseRule(context, styleSheet.get(), "@media all { div { color: pink } }"), 0);
+    styleSheet->wrapperInsertRule(CSSParser::parseRule(context, styleSheet, "@media all { div { color: pink } }"), 0);
     EXPECT_EQ(1U, styleSheet->ruleCount());
     EXPECT_FALSE(styleSheet->hasMediaQueries());
 
-    styleSheet->wrapperInsertRule(CSSParser::parseRule(context, styleSheet.get(), "@media all { div { color: green } }"), 1);
+    styleSheet->wrapperInsertRule(CSSParser::parseRule(context, styleSheet, "@media all { div { color: green } }"), 1);
     EXPECT_EQ(2U, styleSheet->ruleCount());
     EXPECT_TRUE(styleSheet->hasMediaQueries());
 }
diff --git a/third_party/WebKit/Source/core/css/StyleSheetList.h b/third_party/WebKit/Source/core/css/StyleSheetList.h
index b80cb20b..d1280cc8 100644
--- a/third_party/WebKit/Source/core/css/StyleSheetList.h
+++ b/third_party/WebKit/Source/core/css/StyleSheetList.h
@@ -37,7 +37,7 @@
 class StyleSheetList final : public GarbageCollected<StyleSheetList>, public ScriptWrappable {
     DEFINE_WRAPPERTYPEINFO();
 public:
-    static RawPtr<StyleSheetList> create(TreeScope* treeScope) { return new StyleSheetList(treeScope); }
+    static StyleSheetList* create(TreeScope* treeScope) { return new StyleSheetList(treeScope); }
 
     unsigned length();
     StyleSheet* item(unsigned index);
diff --git a/third_party/WebKit/Source/core/css/cssom/KeywordValue.cpp b/third_party/WebKit/Source/core/css/cssom/KeywordValue.cpp
index d39b319..bb3634cb 100644
--- a/third_party/WebKit/Source/core/css/cssom/KeywordValue.cpp
+++ b/third_party/WebKit/Source/core/css/cssom/KeywordValue.cpp
@@ -32,7 +32,7 @@
     return cssValueKeywordID(cssKeywordString);
 }
 
-RawPtr<CSSValue> KeywordValue::toCSSValue() const
+CSSValue* KeywordValue::toCSSValue() const
 {
     CSSValueID keywordID = keywordValueID();
     if (keywordID == CSSValueID::CSSValueInvalid) {
diff --git a/third_party/WebKit/Source/core/css/cssom/KeywordValue.h b/third_party/WebKit/Source/core/css/cssom/KeywordValue.h
index f1872d4..c143db4 100644
--- a/third_party/WebKit/Source/core/css/cssom/KeywordValue.h
+++ b/third_party/WebKit/Source/core/css/cssom/KeywordValue.h
@@ -23,7 +23,7 @@
     const String& keywordValue() const;
     CSSValueID keywordValueID() const;
 
-    RawPtr<CSSValue> toCSSValue() const override;
+    CSSValue* toCSSValue() const override;
 
 private:
     KeywordValue(const String& keyword) : m_keywordValue(keyword) {}
diff --git a/third_party/WebKit/Source/core/css/cssom/MatrixTransformComponent.cpp b/third_party/WebKit/Source/core/css/cssom/MatrixTransformComponent.cpp
index 1410ece..a2d03d66 100644
--- a/third_party/WebKit/Source/core/css/cssom/MatrixTransformComponent.cpp
+++ b/third_party/WebKit/Source/core/css/cssom/MatrixTransformComponent.cpp
@@ -11,9 +11,9 @@
 
 namespace blink {
 
-RawPtr<CSSFunctionValue> MatrixTransformComponent::toCSSValue() const
+CSSFunctionValue* MatrixTransformComponent::toCSSValue() const
 {
-    RawPtr<CSSFunctionValue> result = CSSFunctionValue::create(m_is2D ? CSSValueMatrix : CSSValueMatrix3d);
+    CSSFunctionValue* result = CSSFunctionValue::create(m_is2D ? CSSValueMatrix : CSSValueMatrix3d);
 
     if (m_is2D) {
         double values[6] = {a(), b(), c(), d(), e(), f()};
@@ -28,7 +28,7 @@
         }
     }
 
-    return result.release();
+    return result;
 }
 
 MatrixTransformComponent* MatrixTransformComponent::perspective(double length)
diff --git a/third_party/WebKit/Source/core/css/cssom/MatrixTransformComponent.h b/third_party/WebKit/Source/core/css/cssom/MatrixTransformComponent.h
index 92fd448..6062194 100644
--- a/third_party/WebKit/Source/core/css/cssom/MatrixTransformComponent.h
+++ b/third_party/WebKit/Source/core/css/cssom/MatrixTransformComponent.h
@@ -58,7 +58,7 @@
     // Bindings require a non const return value.
     MatrixTransformComponent* asMatrix() const override { return const_cast<MatrixTransformComponent*>(this); }
 
-    RawPtr<CSSFunctionValue> toCSSValue() const override;
+    CSSFunctionValue* toCSSValue() const override;
 
     static MatrixTransformComponent* perspective(double length);
 
diff --git a/third_party/WebKit/Source/core/css/cssom/NumberValue.h b/third_party/WebKit/Source/core/css/cssom/NumberValue.h
index 5ebdde9..88d45ab4 100644
--- a/third_party/WebKit/Source/core/css/cssom/NumberValue.h
+++ b/third_party/WebKit/Source/core/css/cssom/NumberValue.h
@@ -24,7 +24,7 @@
 
     double value() const { return m_value; }
 
-    RawPtr<CSSValue> toCSSValue() const override
+    CSSValue* toCSSValue() const override
     {
         return cssValuePool().createValue(m_value, CSSPrimitiveValue::UnitType::
 Number);
diff --git a/third_party/WebKit/Source/core/css/cssom/PerspectiveTransformComponent.cpp b/third_party/WebKit/Source/core/css/cssom/PerspectiveTransformComponent.cpp
index 551157c..a7283e4 100644
--- a/third_party/WebKit/Source/core/css/cssom/PerspectiveTransformComponent.cpp
+++ b/third_party/WebKit/Source/core/css/cssom/PerspectiveTransformComponent.cpp
@@ -17,11 +17,11 @@
     return new PerspectiveTransformComponent(length);
 }
 
-RawPtr<CSSFunctionValue> PerspectiveTransformComponent::toCSSValue() const
+CSSFunctionValue* PerspectiveTransformComponent::toCSSValue() const
 {
-    RawPtr<CSSFunctionValue> result = CSSFunctionValue::create(CSSValuePerspective);
+    CSSFunctionValue* result = CSSFunctionValue::create(CSSValuePerspective);
     result->append(m_length->toCSSValue());
-    return result.release();
+    return result;
 }
 
 } // namespace blink
diff --git a/third_party/WebKit/Source/core/css/cssom/PerspectiveTransformComponent.h b/third_party/WebKit/Source/core/css/cssom/PerspectiveTransformComponent.h
index 1f0b55c..40d5533 100644
--- a/third_party/WebKit/Source/core/css/cssom/PerspectiveTransformComponent.h
+++ b/third_party/WebKit/Source/core/css/cssom/PerspectiveTransformComponent.h
@@ -27,7 +27,7 @@
     // TODO: Implement asMatrix for PerspectiveTransformComponent.
     MatrixTransformComponent* asMatrix() const override { return nullptr; }
 
-    RawPtr<CSSFunctionValue> toCSSValue() const override;
+    CSSFunctionValue* toCSSValue() const override;
 
     DEFINE_INLINE_VIRTUAL_TRACE()
     {
diff --git a/third_party/WebKit/Source/core/css/cssom/PositionValue.cpp b/third_party/WebKit/Source/core/css/cssom/PositionValue.cpp
index 69e1589..282f4a8 100644
--- a/third_party/WebKit/Source/core/css/cssom/PositionValue.cpp
+++ b/third_party/WebKit/Source/core/css/cssom/PositionValue.cpp
@@ -9,7 +9,7 @@
 
 namespace blink {
 
-RawPtr<CSSValue> PositionValue::toCSSValue() const
+CSSValue* PositionValue::toCSSValue() const
 {
     return CSSValuePair::create(m_x->toCSSValue(), m_y->toCSSValue(), CSSValuePair::KeepIdenticalValues);
 }
diff --git a/third_party/WebKit/Source/core/css/cssom/PositionValue.h b/third_party/WebKit/Source/core/css/cssom/PositionValue.h
index e8afaa60..c4f01705 100644
--- a/third_party/WebKit/Source/core/css/cssom/PositionValue.h
+++ b/third_party/WebKit/Source/core/css/cssom/PositionValue.h
@@ -28,7 +28,7 @@
 
     StyleValueType type() const override { return PositionType; }
 
-    RawPtr<CSSValue> toCSSValue() const override;
+    CSSValue* toCSSValue() const override;
 
     DEFINE_INLINE_VIRTUAL_TRACE()
     {
diff --git a/third_party/WebKit/Source/core/css/cssom/RotationTransformComponent.cpp b/third_party/WebKit/Source/core/css/cssom/RotationTransformComponent.cpp
index 312ce42..177d345e8 100644
--- a/third_party/WebKit/Source/core/css/cssom/RotationTransformComponent.cpp
+++ b/third_party/WebKit/Source/core/css/cssom/RotationTransformComponent.cpp
@@ -9,16 +9,16 @@
 
 namespace blink {
 
-RawPtr<CSSFunctionValue> RotationTransformComponent::toCSSValue() const
+CSSFunctionValue* RotationTransformComponent::toCSSValue() const
 {
-    RawPtr<CSSFunctionValue> result = CSSFunctionValue::create(m_is2D ? CSSValueRotate : CSSValueRotate3d);
+    CSSFunctionValue* result = CSSFunctionValue::create(m_is2D ? CSSValueRotate : CSSValueRotate3d);
     if (!m_is2D) {
         result->append(cssValuePool().createValue(m_x, CSSPrimitiveValue::UnitType::Number));
         result->append(cssValuePool().createValue(m_y, CSSPrimitiveValue::UnitType::Number));
         result->append(cssValuePool().createValue(m_z, CSSPrimitiveValue::UnitType::Number));
     }
     result->append(cssValuePool().createValue(m_angle, CSSPrimitiveValue::UnitType::Degrees));
-    return result.release();
+    return result;
 }
 
 } // namespace blink
diff --git a/third_party/WebKit/Source/core/css/cssom/RotationTransformComponent.h b/third_party/WebKit/Source/core/css/cssom/RotationTransformComponent.h
index c59badb..cddacc0 100644
--- a/third_party/WebKit/Source/core/css/cssom/RotationTransformComponent.h
+++ b/third_party/WebKit/Source/core/css/cssom/RotationTransformComponent.h
@@ -37,7 +37,7 @@
             : MatrixTransformComponent::rotate3d(m_angle, m_x, m_y, m_z);
     }
 
-    RawPtr<CSSFunctionValue> toCSSValue() const override;
+    CSSFunctionValue* toCSSValue() const override;
 
 private:
     RotationTransformComponent(double angle)
diff --git a/third_party/WebKit/Source/core/css/cssom/ScaleTransformComponent.cpp b/third_party/WebKit/Source/core/css/cssom/ScaleTransformComponent.cpp
index fe5353aa..019a398f 100644
--- a/third_party/WebKit/Source/core/css/cssom/ScaleTransformComponent.cpp
+++ b/third_party/WebKit/Source/core/css/cssom/ScaleTransformComponent.cpp
@@ -9,16 +9,16 @@
 
 namespace blink {
 
-RawPtr<CSSFunctionValue> ScaleTransformComponent::toCSSValue() const
+CSSFunctionValue* ScaleTransformComponent::toCSSValue() const
 {
-    RawPtr<CSSFunctionValue> result = CSSFunctionValue::create(m_is2D ? CSSValueScale : CSSValueScale3d);
+    CSSFunctionValue* result = CSSFunctionValue::create(m_is2D ? CSSValueScale : CSSValueScale3d);
 
     result->append(cssValuePool().createValue(m_x, CSSPrimitiveValue::UnitType::Number));
     result->append(cssValuePool().createValue(m_y, CSSPrimitiveValue::UnitType::Number));
     if (!m_is2D)
         result->append(cssValuePool().createValue(m_z, CSSPrimitiveValue::UnitType::Number));
 
-    return result.release();
+    return result;
 }
 
 } // namespace blink
diff --git a/third_party/WebKit/Source/core/css/cssom/ScaleTransformComponent.h b/third_party/WebKit/Source/core/css/cssom/ScaleTransformComponent.h
index 836158f5..1f52eb2a3 100644
--- a/third_party/WebKit/Source/core/css/cssom/ScaleTransformComponent.h
+++ b/third_party/WebKit/Source/core/css/cssom/ScaleTransformComponent.h
@@ -36,7 +36,7 @@
             : MatrixTransformComponent::scale3d(m_x, m_y, m_z);
     }
 
-    RawPtr<CSSFunctionValue> toCSSValue() const override;
+    CSSFunctionValue* toCSSValue() const override;
 
 private:
     ScaleTransformComponent(double x, double y) : m_x(x), m_y(y), m_z(1), m_is2D(true) { }
diff --git a/third_party/WebKit/Source/core/css/cssom/SimpleLength.cpp b/third_party/WebKit/Source/core/css/cssom/SimpleLength.cpp
index e1f8e0b6..ccb71cb 100644
--- a/third_party/WebKit/Source/core/css/cssom/SimpleLength.cpp
+++ b/third_party/WebKit/Source/core/css/cssom/SimpleLength.cpp
@@ -10,7 +10,7 @@
 
 namespace blink {
 
-RawPtr<CSSValue> SimpleLength::toCSSValue() const
+CSSValue* SimpleLength::toCSSValue() const
 {
     return cssValuePool().createValue(m_value, m_unit);
 }
diff --git a/third_party/WebKit/Source/core/css/cssom/SimpleLength.h b/third_party/WebKit/Source/core/css/cssom/SimpleLength.h
index 133d67e..a9b221f 100644
--- a/third_party/WebKit/Source/core/css/cssom/SimpleLength.h
+++ b/third_party/WebKit/Source/core/css/cssom/SimpleLength.h
@@ -41,7 +41,7 @@
 
     StyleValueType type() const override { return StyleValueType::SimpleLengthType; }
 
-    RawPtr<CSSValue> toCSSValue() const override;
+    CSSValue* toCSSValue() const override;
 
 protected:
     virtual LengthValue* addInternal(const LengthValue* other, ExceptionState&);
diff --git a/third_party/WebKit/Source/core/css/cssom/SkewTransformComponent.cpp b/third_party/WebKit/Source/core/css/cssom/SkewTransformComponent.cpp
index 429f0ffc..bc03c56 100644
--- a/third_party/WebKit/Source/core/css/cssom/SkewTransformComponent.cpp
+++ b/third_party/WebKit/Source/core/css/cssom/SkewTransformComponent.cpp
@@ -9,12 +9,12 @@
 
 namespace blink {
 
-RawPtr<CSSFunctionValue> SkewTransformComponent::toCSSValue() const
+CSSFunctionValue* SkewTransformComponent::toCSSValue() const
 {
-    RawPtr<CSSFunctionValue> result = CSSFunctionValue::create(CSSValueSkew);
+    CSSFunctionValue* result = CSSFunctionValue::create(CSSValueSkew);
     result->append(cssValuePool().createValue(m_ax, CSSPrimitiveValue::UnitType::Number));
     result->append(cssValuePool().createValue(m_ay, CSSPrimitiveValue::UnitType::Number));
-    return result.release();
+    return result;
 }
 
 } // namespace blink
diff --git a/third_party/WebKit/Source/core/css/cssom/SkewTransformComponent.h b/third_party/WebKit/Source/core/css/cssom/SkewTransformComponent.h
index 49db2da..a6fd9bcd 100644
--- a/third_party/WebKit/Source/core/css/cssom/SkewTransformComponent.h
+++ b/third_party/WebKit/Source/core/css/cssom/SkewTransformComponent.h
@@ -29,7 +29,7 @@
         return MatrixTransformComponent::skew(m_ax, m_ay);
     }
 
-    RawPtr<CSSFunctionValue> toCSSValue() const override;
+    CSSFunctionValue* toCSSValue() const override;
 
 private:
     SkewTransformComponent(double ax, double ay) : TransformComponent(), m_ax(ax), m_ay(ay) { }
diff --git a/third_party/WebKit/Source/core/css/cssom/StyleCalcLength.cpp b/third_party/WebKit/Source/core/css/cssom/StyleCalcLength.cpp
index a2a656a..fc2c550 100644
--- a/third_party/WebKit/Source/core/css/cssom/StyleCalcLength.cpp
+++ b/third_party/WebKit/Source/core/css/cssom/StyleCalcLength.cpp
@@ -123,10 +123,10 @@
     return result;
 }
 
-RawPtr<CSSValue> StyleCalcLength::toCSSValue() const
+CSSValue* StyleCalcLength::toCSSValue() const
 {
     // Create a CSS Calc Value, then put it into a CSSPrimitiveValue
-    RawPtr<CSSCalcExpressionNode> node = nullptr;
+    CSSCalcExpressionNode* node = nullptr;
     for (unsigned i = 0; i < LengthValue::kNumSupportedUnits; ++i) {
         if (!hasAtIndex(i))
             continue;
diff --git a/third_party/WebKit/Source/core/css/cssom/StyleCalcLength.h b/third_party/WebKit/Source/core/css/cssom/StyleCalcLength.h
index 491de69..3ef6670 100644
--- a/third_party/WebKit/Source/core/css/cssom/StyleCalcLength.h
+++ b/third_party/WebKit/Source/core/css/cssom/StyleCalcLength.h
@@ -50,7 +50,7 @@
 
     bool containsPercent() const override;
 
-    RawPtr<CSSValue> toCSSValue() const override;
+    CSSValue* toCSSValue() const override;
 
     StyleValueType type() const override { return CalcLengthType; }
 protected:
diff --git a/third_party/WebKit/Source/core/css/cssom/StyleValue.h b/third_party/WebKit/Source/core/css/cssom/StyleValue.h
index 6997319..214dd9e 100644
--- a/third_party/WebKit/Source/core/css/cssom/StyleValue.h
+++ b/third_party/WebKit/Source/core/css/cssom/StyleValue.h
@@ -29,7 +29,7 @@
 
     static ScriptValue parse(ScriptState*, const String& property, const String& cssText);
 
-    virtual RawPtr<CSSValue> toCSSValue() const = 0;
+    virtual CSSValue* toCSSValue() const = 0;
     virtual String cssString() const
     {
         return toCSSValue()->cssText();
diff --git a/third_party/WebKit/Source/core/css/cssom/TransformComponent.h b/third_party/WebKit/Source/core/css/cssom/TransformComponent.h
index 29affcf..acf7067 100644
--- a/third_party/WebKit/Source/core/css/cssom/TransformComponent.h
+++ b/third_party/WebKit/Source/core/css/cssom/TransformComponent.h
@@ -42,7 +42,7 @@
         return toCSSValue()->cssText();
     }
 
-    virtual RawPtr<CSSFunctionValue> toCSSValue() const = 0;
+    virtual CSSFunctionValue* toCSSValue() const = 0;
     virtual MatrixTransformComponent* asMatrix() const = 0;
 
     DEFINE_INLINE_VIRTUAL_TRACE() { }
diff --git a/third_party/WebKit/Source/core/css/cssom/TransformValue.cpp b/third_party/WebKit/Source/core/css/cssom/TransformValue.cpp
index bcc17bd..9184695 100644
--- a/third_party/WebKit/Source/core/css/cssom/TransformValue.cpp
+++ b/third_party/WebKit/Source/core/css/cssom/TransformValue.cpp
@@ -54,9 +54,9 @@
     return true;
 }
 
-RawPtr<CSSValue> TransformValue::toCSSValue() const
+CSSValue* TransformValue::toCSSValue() const
 {
-    RawPtr<CSSValueList> transformCSSValue = CSSValueList::createSpaceSeparated();
+    CSSValueList* transformCSSValue = CSSValueList::createSpaceSeparated();
     for (size_t i = 0; i < m_transformComponents.size(); i++) {
         transformCSSValue->append(m_transformComponents[i]->toCSSValue());
     }
diff --git a/third_party/WebKit/Source/core/css/cssom/TransformValue.h b/third_party/WebKit/Source/core/css/cssom/TransformValue.h
index 993bd0a..9d97ce0 100644
--- a/third_party/WebKit/Source/core/css/cssom/TransformValue.h
+++ b/third_party/WebKit/Source/core/css/cssom/TransformValue.h
@@ -31,7 +31,7 @@
 
     bool is2D() const;
 
-    RawPtr<CSSValue> toCSSValue() const override;
+    CSSValue* toCSSValue() const override;
 
     StyleValueType type() const override { return TransformValueType; }
 
diff --git a/third_party/WebKit/Source/core/css/cssom/TranslationTransformComponent.cpp b/third_party/WebKit/Source/core/css/cssom/TranslationTransformComponent.cpp
index 7cc1466..d7c2617 100644
--- a/third_party/WebKit/Source/core/css/cssom/TranslationTransformComponent.cpp
+++ b/third_party/WebKit/Source/core/css/cssom/TranslationTransformComponent.cpp
@@ -19,14 +19,14 @@
     return new TranslationTransformComponent(x, y, z);
 }
 
-RawPtr<CSSFunctionValue> TranslationTransformComponent::toCSSValue() const
+CSSFunctionValue* TranslationTransformComponent::toCSSValue() const
 {
-    RawPtr<CSSFunctionValue> result = CSSFunctionValue::create(is2D() ? CSSValueTranslate : CSSValueTranslate3d);
+    CSSFunctionValue* result = CSSFunctionValue::create(is2D() ? CSSValueTranslate : CSSValueTranslate3d);
     result->append(m_x->toCSSValue());
     result->append(m_y->toCSSValue());
     if (!is2D())
         result->append(m_z->toCSSValue());
-    return result.release();
+    return result;
 }
 
 } // namespace blink
diff --git a/third_party/WebKit/Source/core/css/cssom/TranslationTransformComponent.h b/third_party/WebKit/Source/core/css/cssom/TranslationTransformComponent.h
index 3f62ea16..9e84421 100644
--- a/third_party/WebKit/Source/core/css/cssom/TranslationTransformComponent.h
+++ b/third_party/WebKit/Source/core/css/cssom/TranslationTransformComponent.h
@@ -31,7 +31,7 @@
     // TODO: Implement asMatrix for TranslationTransformComponent.
     MatrixTransformComponent* asMatrix() const override { return nullptr; }
 
-    RawPtr<CSSFunctionValue> toCSSValue() const override;
+    CSSFunctionValue* toCSSValue() const override;
 
     DEFINE_INLINE_VIRTUAL_TRACE()
     {
diff --git a/third_party/WebKit/Source/core/css/parser/CSSParser.cpp b/third_party/WebKit/Source/core/css/parser/CSSParser.cpp
index 07522604..6f892e0 100644
--- a/third_party/WebKit/Source/core/css/parser/CSSParser.cpp
+++ b/third_party/WebKit/Source/core/css/parser/CSSParser.cpp
@@ -43,7 +43,7 @@
     return CSSParserImpl::parsePageSelector(scope.tokenRange(), styleSheetContents);
 }
 
-RawPtr<StyleRuleBase> CSSParser::parseRule(const CSSParserContext& context, StyleSheetContents* styleSheet, const String& rule)
+StyleRuleBase* CSSParser::parseRule(const CSSParserContext& context, StyleSheetContents* styleSheet, const String& rule)
 {
     return CSSParserImpl::parseRule(rule, context, styleSheet, CSSParserImpl::AllowImportRules);
 }
@@ -64,9 +64,9 @@
         return false;
     CSSPropertyID resolvedProperty = resolveCSSPropertyID(unresolvedProperty);
     CSSParserMode parserMode = declaration->cssParserMode();
-    RawPtr<CSSValue> value = CSSParserFastPaths::maybeParseValue(resolvedProperty, string, parserMode);
+    CSSValue* value = CSSParserFastPaths::maybeParseValue(resolvedProperty, string, parserMode);
     if (value)
-        return declaration->setProperty(CSSProperty(resolvedProperty, value.release(), important));
+        return declaration->setProperty(CSSProperty(resolvedProperty, value, important));
     CSSParserContext context(parserMode, 0);
     if (styleSheet) {
         context = styleSheet->parserContext();
@@ -89,7 +89,7 @@
     return CSSParserImpl::parseVariableValue(declaration, propertyName, value, important, context);
 }
 
-RawPtr<ImmutableStylePropertySet> CSSParser::parseCustomPropertySet(CSSParserTokenRange range)
+ImmutableStylePropertySet* CSSParser::parseCustomPropertySet(CSSParserTokenRange range)
 {
     return CSSParserImpl::parseCustomPropertySet(range);
 }
@@ -99,17 +99,17 @@
     return CSSParserImpl::parseValue(declaration, unresolvedProperty, string, important, context);
 }
 
-RawPtr<CSSValue> CSSParser::parseSingleValue(CSSPropertyID propertyID, const String& string, const CSSParserContext& context)
+CSSValue* CSSParser::parseSingleValue(CSSPropertyID propertyID, const String& string, const CSSParserContext& context)
 {
     if (string.isEmpty())
         return nullptr;
-    if (RawPtr<CSSValue> value = CSSParserFastPaths::maybeParseValue(propertyID, string, context.mode()))
+    if (CSSValue* value = CSSParserFastPaths::maybeParseValue(propertyID, string, context.mode()))
         return value;
     CSSTokenizer::Scope scope(string);
     return CSSPropertyParser::parseSingleValue(propertyID, scope.tokenRange(), context);
 }
 
-RawPtr<ImmutableStylePropertySet> CSSParser::parseInlineStyleDeclaration(const String& styleString, Element* element)
+ImmutableStylePropertySet* CSSParser::parseInlineStyleDeclaration(const String& styleString, Element* element)
 {
     return CSSParserImpl::parseInlineStyleDeclaration(styleString, element);
 }
@@ -119,10 +119,10 @@
     return CSSParserImpl::parseKeyframeKeyList(keyList);
 }
 
-RawPtr<StyleRuleKeyframe> CSSParser::parseKeyframeRule(const CSSParserContext& context, const String& rule)
+StyleRuleKeyframe* CSSParser::parseKeyframeRule(const CSSParserContext& context, const String& rule)
 {
-    RawPtr<StyleRuleBase> keyframe = CSSParserImpl::parseRule(rule, context, nullptr, CSSParserImpl::KeyframeRules);
-    return toStyleRuleKeyframe(keyframe.get());
+    StyleRuleBase* keyframe = CSSParserImpl::parseRule(rule, context, nullptr, CSSParserImpl::KeyframeRules);
+    return toStyleRuleKeyframe(keyframe);
 }
 
 bool CSSParser::parseSupportsCondition(const String& condition)
@@ -145,7 +145,7 @@
         return true;
     }
 
-    RawPtr<CSSValue> value = CSSParserFastPaths::parseColor(string, strict ? HTMLStandardMode : HTMLQuirksMode);
+    CSSValue* value = CSSParserFastPaths::parseColor(string, strict ? HTMLStandardMode : HTMLQuirksMode);
     // TODO(timloh): Why is this always strict mode?
     if (!value)
         value = parseSingleValue(CSSPropertyColor, string, strictCSSParserContext());
@@ -168,7 +168,7 @@
     return true;
 }
 
-RawPtr<CSSValue> CSSParser::parseFontFaceDescriptor(CSSPropertyID propertyID, const String& propertyValue, const CSSParserContext& context)
+CSSValue* CSSParser::parseFontFaceDescriptor(CSSPropertyID propertyID, const String& propertyValue, const CSSParserContext& context)
 {
     StringBuilder builder;
     builder.appendLiteral("@font-face { ");
@@ -176,10 +176,10 @@
     builder.appendLiteral(" : ");
     builder.append(propertyValue);
     builder.appendLiteral("; }");
-    RawPtr<StyleRuleBase> rule = parseRule(context, nullptr, builder.toString());
+    StyleRuleBase* rule = parseRule(context, nullptr, builder.toString());
     if (!rule || !rule->isFontFaceRule())
         return nullptr;
-    return toStyleRuleFontFace(rule.get())->properties().getPropertyCSSValue(propertyID);
+    return toStyleRuleFontFace(rule)->properties().getPropertyCSSValue(propertyID);
 }
 
 } // namespace blink
diff --git a/third_party/WebKit/Source/core/css/parser/CSSParser.h b/third_party/WebKit/Source/core/css/parser/CSSParser.h
index af98f80..341a2d58 100644
--- a/third_party/WebKit/Source/core/css/parser/CSSParser.h
+++ b/third_party/WebKit/Source/core/css/parser/CSSParser.h
@@ -29,7 +29,7 @@
     STATIC_ONLY(CSSParser);
 public:
     // As well as regular rules, allows @import and @namespace but not @charset
-    static RawPtr<StyleRuleBase> parseRule(const CSSParserContext&, StyleSheetContents*, const String&);
+    static StyleRuleBase* parseRule(const CSSParserContext&, StyleSheetContents*, const String&);
     static void parseSheet(const CSSParserContext&, StyleSheetContents*, const String&);
     static CSSSelectorList parseSelector(const CSSParserContext&, StyleSheetContents*, const String&);
     static CSSSelectorList parsePageSelector(const CSSParserContext&, StyleSheetContents*, const String&);
@@ -38,17 +38,17 @@
     static bool parseValue(MutableStylePropertySet*, CSSPropertyID unresolvedProperty, const String&, bool important, StyleSheetContents*);
 
     static bool parseValueForCustomProperty(MutableStylePropertySet*, const AtomicString& propertyName, const String& value, bool important, StyleSheetContents*);
-    static RawPtr<ImmutableStylePropertySet> parseCustomPropertySet(CSSParserTokenRange);
+    static ImmutableStylePropertySet* parseCustomPropertySet(CSSParserTokenRange);
 
     // This is for non-shorthands only
-    static RawPtr<CSSValue> parseSingleValue(CSSPropertyID, const String&, const CSSParserContext& = strictCSSParserContext());
+    static CSSValue* parseSingleValue(CSSPropertyID, const String&, const CSSParserContext& = strictCSSParserContext());
 
-    static RawPtr<CSSValue> parseFontFaceDescriptor(CSSPropertyID, const String&, const CSSParserContext&);
+    static CSSValue* parseFontFaceDescriptor(CSSPropertyID, const String&, const CSSParserContext&);
 
-    static RawPtr<ImmutableStylePropertySet> parseInlineStyleDeclaration(const String&, Element*);
+    static ImmutableStylePropertySet* parseInlineStyleDeclaration(const String&, Element*);
 
     static PassOwnPtr<Vector<double>> parseKeyframeKeyList(const String&);
-    static RawPtr<StyleRuleKeyframe> parseKeyframeRule(const CSSParserContext&, const String&);
+    static StyleRuleKeyframe* parseKeyframeRule(const CSSParserContext&, const String&);
 
     static bool parseSupportsCondition(const String&);
 
diff --git a/third_party/WebKit/Source/core/css/parser/CSSParserFastPaths.cpp b/third_party/WebKit/Source/core/css/parser/CSSParserFastPaths.cpp
index 4eb704a..768add5 100644
--- a/third_party/WebKit/Source/core/css/parser/CSSParserFastPaths.cpp
+++ b/third_party/WebKit/Source/core/css/parser/CSSParserFastPaths.cpp
@@ -86,7 +86,7 @@
     return ok && CSSPropertyParser::isValidNumericValue(number);
 }
 
-static RawPtr<CSSValue> parseSimpleLengthValue(CSSPropertyID propertyId, const String& string, CSSParserMode cssParserMode)
+static CSSValue* parseSimpleLengthValue(CSSPropertyID propertyId, const String& string, CSSParserMode cssParserMode)
 {
     ASSERT(!string.isEmpty());
     bool acceptsNegativeNumbers = false;
@@ -437,7 +437,7 @@
     return false;
 }
 
-RawPtr<CSSValue> CSSParserFastPaths::parseColor(const String& string, CSSParserMode parserMode)
+CSSValue* CSSParserFastPaths::parseColor(const String& string, CSSParserMode parserMode)
 {
     ASSERT(!string.isEmpty());
     CSSParserString cssString;
@@ -828,7 +828,7 @@
     }
 }
 
-static RawPtr<CSSValue> parseKeywordValue(CSSPropertyID propertyId, const String& string)
+static CSSValue* parseKeywordValue(CSSPropertyID propertyId, const String& string)
 {
     ASSERT(!string.isEmpty());
 
@@ -900,7 +900,7 @@
 }
 
 template <typename CharType>
-static RawPtr<CSSFunctionValue> parseSimpleTransformValue(CharType*& pos, CharType* end)
+static CSSFunctionValue* parseSimpleTransformValue(CharType*& pos, CharType* end)
 {
     static const int shortestValidTransformStringLength = 12;
 
@@ -940,10 +940,10 @@
             return nullptr;
         }
         pos += argumentStart;
-        RawPtr<CSSFunctionValue> transformValue = CSSFunctionValue::create(transformType);
-        if (!parseTransformTranslateArguments(pos, end, expectedArgumentCount, transformValue.get()))
+        CSSFunctionValue* transformValue = CSSFunctionValue::create(transformType);
+        if (!parseTransformTranslateArguments(pos, end, expectedArgumentCount, transformValue))
             return nullptr;
-        return transformValue.release();
+        return transformValue;
     }
 
     const bool isMatrix3d = toASCIILower(pos[0]) == 'm'
@@ -958,10 +958,10 @@
 
     if (isMatrix3d) {
         pos += 9;
-        RawPtr<CSSFunctionValue> transformValue = CSSFunctionValue::create(CSSValueMatrix3d);
-        if (!parseTransformNumberArguments(pos, end, 16, transformValue.get()))
+        CSSFunctionValue* transformValue = CSSFunctionValue::create(CSSValueMatrix3d);
+        if (!parseTransformNumberArguments(pos, end, 16, transformValue))
             return nullptr;
-        return transformValue.release();
+        return transformValue;
     }
 
     const bool isScale3d = toASCIILower(pos[0]) == 's'
@@ -975,37 +975,37 @@
 
     if (isScale3d) {
         pos += 8;
-        RawPtr<CSSFunctionValue> transformValue = CSSFunctionValue::create(CSSValueScale3d);
-        if (!parseTransformNumberArguments(pos, end, 3, transformValue.get()))
+        CSSFunctionValue* transformValue = CSSFunctionValue::create(CSSValueScale3d);
+        if (!parseTransformNumberArguments(pos, end, 3, transformValue))
             return nullptr;
-        return transformValue.release();
+        return transformValue;
     }
 
     return nullptr;
 }
 
 template <typename CharType>
-static RawPtr<CSSValueList> parseSimpleTransformList(CharType*& pos, CharType* end)
+static CSSValueList* parseSimpleTransformList(CharType*& pos, CharType* end)
 {
-    RawPtr<CSSValueList> transformList = nullptr;
+    CSSValueList* transformList = nullptr;
     while (pos < end) {
         while (pos < end && isCSSSpace(*pos))
             ++pos;
-        RawPtr<CSSFunctionValue> transformValue = parseSimpleTransformValue(pos, end);
+        CSSFunctionValue* transformValue = parseSimpleTransformValue(pos, end);
         if (!transformValue)
             return nullptr;
         if (!transformList)
             transformList = CSSValueList::createSpaceSeparated();
-        transformList->append(transformValue.release());
+        transformList->append(transformValue);
         if (pos < end) {
             if (isCSSSpace(*pos))
                 return nullptr;
         }
     }
-    return transformList.release();
+    return transformList;
 }
 
-static RawPtr<CSSValue> parseSimpleTransform(CSSPropertyID propertyID, const String& string)
+static CSSValue* parseSimpleTransform(CSSPropertyID propertyID, const String& string)
 {
     ASSERT(!string.isEmpty());
 
@@ -1021,16 +1021,16 @@
     return parseSimpleTransformList(pos, end);
 }
 
-RawPtr<CSSValue> CSSParserFastPaths::maybeParseValue(CSSPropertyID propertyID, const String& string, CSSParserMode parserMode)
+CSSValue* CSSParserFastPaths::maybeParseValue(CSSPropertyID propertyID, const String& string, CSSParserMode parserMode)
 {
-    if (RawPtr<CSSValue> length = parseSimpleLengthValue(propertyID, string, parserMode))
-        return length.release();
+    if (CSSValue* length = parseSimpleLengthValue(propertyID, string, parserMode))
+        return length;
     if (isColorPropertyID(propertyID))
         return parseColor(string, parserMode);
-    if (RawPtr<CSSValue> keyword = parseKeywordValue(propertyID, string))
-        return keyword.release();
-    if (RawPtr<CSSValue> transform = parseSimpleTransform(propertyID, string))
-        return transform.release();
+    if (CSSValue* keyword = parseKeywordValue(propertyID, string))
+        return keyword;
+    if (CSSValue* transform = parseSimpleTransform(propertyID, string))
+        return transform;
     return nullptr;
 }
 
diff --git a/third_party/WebKit/Source/core/css/parser/CSSParserFastPaths.h b/third_party/WebKit/Source/core/css/parser/CSSParserFastPaths.h
index 5d43a5c..54e065f 100644
--- a/third_party/WebKit/Source/core/css/parser/CSSParserFastPaths.h
+++ b/third_party/WebKit/Source/core/css/parser/CSSParserFastPaths.h
@@ -21,13 +21,13 @@
 public:
     // Parses simple values like '10px' or 'green', but makes no guarantees
     // about handling any property completely.
-    static RawPtr<CSSValue> maybeParseValue(CSSPropertyID, const String&, CSSParserMode);
+    static CSSValue* maybeParseValue(CSSPropertyID, const String&, CSSParserMode);
 
     // Properties handled here shouldn't be explicitly handled in CSSPropertyParser
     static bool isKeywordPropertyID(CSSPropertyID);
     static bool isValidKeywordPropertyAndValue(CSSPropertyID, CSSValueID);
 
-    static RawPtr<CSSValue> parseColor(const String&, CSSParserMode);
+    static CSSValue* parseColor(const String&, CSSParserMode);
 };
 
 } // namespace blink
diff --git a/third_party/WebKit/Source/core/css/parser/CSSParserImpl.cpp b/third_party/WebKit/Source/core/css/parser/CSSParserImpl.cpp
index 69b192bcb7..d4fde0f 100644
--- a/third_party/WebKit/Source/core/css/parser/CSSParserImpl.cpp
+++ b/third_party/WebKit/Source/core/css/parser/CSSParserImpl.cpp
@@ -87,7 +87,7 @@
     }
 }
 
-static RawPtr<ImmutableStylePropertySet> createStylePropertySet(HeapVector<CSSProperty, 256>& parsedProperties, CSSParserMode mode)
+static ImmutableStylePropertySet* createStylePropertySet(HeapVector<CSSProperty, 256>& parsedProperties, CSSParserMode mode)
 {
     std::bitset<numCSSProperties> seenProperties;
     size_t unusedEntries = parsedProperties.size();
@@ -97,12 +97,12 @@
     filterProperties(true, parsedProperties, results, unusedEntries, seenProperties, seenCustomProperties);
     filterProperties(false, parsedProperties, results, unusedEntries, seenProperties, seenCustomProperties);
 
-    RawPtr<ImmutableStylePropertySet> result = ImmutableStylePropertySet::create(results.data() + unusedEntries, results.size() - unusedEntries, mode);
+    ImmutableStylePropertySet* result = ImmutableStylePropertySet::create(results.data() + unusedEntries, results.size() - unusedEntries, mode);
     parsedProperties.clear();
-    return result.release();
+    return result;
 }
 
-RawPtr<ImmutableStylePropertySet> CSSParserImpl::parseInlineStyleDeclaration(const String& string, Element* element)
+ImmutableStylePropertySet* CSSParserImpl::parseInlineStyleDeclaration(const String& string, Element* element)
 {
     Document& document = element->document();
     CSSParserContext context = CSSParserContext(document.elementSheet().contents()->parserContext(), UseCounter::getFrom(&document));
@@ -136,7 +136,7 @@
     return declaration->addParsedProperties(results);
 }
 
-RawPtr<StyleRuleBase> CSSParserImpl::parseRule(const String& string, const CSSParserContext& context, StyleSheetContents* styleSheet, AllowedRulesType allowedRules)
+StyleRuleBase* CSSParserImpl::parseRule(const String& string, const CSSParserContext& context, StyleSheetContents* styleSheet, AllowedRulesType allowedRules)
 {
     CSSParserImpl parser(context, styleSheet);
     CSSTokenizer::Scope scope(string);
@@ -144,7 +144,7 @@
     range.consumeWhitespace();
     if (range.atEnd())
         return nullptr; // Parse error, empty rule
-    RawPtr<StyleRuleBase> rule;
+    StyleRuleBase* rule;
     if (range.peek().type() == AtKeywordToken)
         rule = parser.consumeAtRule(range, allowedRules);
     else
@@ -170,7 +170,7 @@
 
     TRACE_EVENT_BEGIN0("blink,blink_style", "CSSParserImpl::parseStyleSheet.parse");
     CSSParserImpl parser(context, styleSheet);
-    bool firstRuleValid = parser.consumeRuleList(scope.tokenRange(), TopLevelRuleList, [&styleSheet](RawPtr<StyleRuleBase> rule) {
+    bool firstRuleValid = parser.consumeRuleList(scope.tokenRange(), TopLevelRuleList, [&styleSheet](StyleRuleBase* rule) {
         if (rule->isCharsetRule())
             return;
         styleSheet->parserAppendRule(rule);
@@ -227,7 +227,7 @@
     return selectorList;
 }
 
-RawPtr<ImmutableStylePropertySet> CSSParserImpl::parseCustomPropertySet(CSSParserTokenRange range)
+ImmutableStylePropertySet* CSSParserImpl::parseCustomPropertySet(CSSParserTokenRange range)
 {
     range.consumeWhitespace();
     if (range.peek().type() != LeftBraceToken)
@@ -280,7 +280,7 @@
     CSSParserObserverWrapper wrapper(observer);
     parser.m_observerWrapper = &wrapper;
     CSSTokenizer::Scope scope(string, wrapper);
-    bool firstRuleValid = parser.consumeRuleList(scope.tokenRange(), TopLevelRuleList, [&styleSheet](RawPtr<StyleRuleBase> rule) {
+    bool firstRuleValid = parser.consumeRuleList(scope.tokenRange(), TopLevelRuleList, [&styleSheet](StyleRuleBase* rule) {
         if (rule->isCharsetRule())
             return;
         styleSheet->parserAppendRule(rule);
@@ -321,7 +321,7 @@
     bool seenRule = false;
     bool firstRuleValid = false;
     while (!range.atEnd()) {
-        RawPtr<StyleRuleBase> rule;
+        StyleRuleBase* rule;
         switch (range.peek().type()) {
         case WhitespaceToken:
             range.consumeWhitespace();
@@ -345,15 +345,15 @@
             firstRuleValid = rule;
         }
         if (rule) {
-            allowedRules = computeNewAllowedRules(allowedRules, rule.get());
-            callback(rule.release());
+            allowedRules = computeNewAllowedRules(allowedRules, rule);
+            callback(rule);
         }
     }
 
     return firstRuleValid;
 }
 
-RawPtr<StyleRuleBase> CSSParserImpl::consumeAtRule(CSSParserTokenRange& range, AllowedRulesType allowedRules)
+StyleRuleBase* CSSParserImpl::consumeAtRule(CSSParserTokenRange& range, AllowedRulesType allowedRules)
 {
     ASSERT(range.peek().type() == AtKeywordToken);
     const CSSParserString& name = range.consume().value();
@@ -409,7 +409,7 @@
     }
 }
 
-RawPtr<StyleRuleBase> CSSParserImpl::consumeQualifiedRule(CSSParserTokenRange& range, AllowedRulesType allowedRules)
+StyleRuleBase* CSSParserImpl::consumeQualifiedRule(CSSParserTokenRange& range, AllowedRulesType allowedRules)
 {
     const CSSParserToken* preludeStart = &range.peek();
     while (!range.atEnd() && range.peek().type() != LeftBraceToken)
@@ -449,7 +449,7 @@
     return uri.value();
 }
 
-RawPtr<StyleRuleCharset> CSSParserImpl::consumeCharsetRule(CSSParserTokenRange prelude)
+StyleRuleCharset* CSSParserImpl::consumeCharsetRule(CSSParserTokenRange prelude)
 {
     prelude.consumeWhitespace();
     const CSSParserToken& string = prelude.consumeIncludingWhitespace();
@@ -458,7 +458,7 @@
     return StyleRuleCharset::create();
 }
 
-RawPtr<StyleRuleImport> CSSParserImpl::consumeImportRule(CSSParserTokenRange prelude)
+StyleRuleImport* CSSParserImpl::consumeImportRule(CSSParserTokenRange prelude)
 {
     prelude.consumeWhitespace();
     AtomicString uri(consumeStringOrURI(prelude));
@@ -476,7 +476,7 @@
     return StyleRuleImport::create(uri, MediaQueryParser::parseMediaQuerySet(prelude));
 }
 
-RawPtr<StyleRuleNamespace> CSSParserImpl::consumeNamespaceRule(CSSParserTokenRange prelude)
+StyleRuleNamespace* CSSParserImpl::consumeNamespaceRule(CSSParserTokenRange prelude)
 {
     prelude.consumeWhitespace();
     AtomicString namespacePrefix;
@@ -491,7 +491,7 @@
     return StyleRuleNamespace::create(namespacePrefix, uri);
 }
 
-RawPtr<StyleRuleMedia> CSSParserImpl::consumeMediaRule(CSSParserTokenRange prelude, CSSParserTokenRange block)
+StyleRuleMedia* CSSParserImpl::consumeMediaRule(CSSParserTokenRange prelude, CSSParserTokenRange block)
 {
     HeapVector<Member<StyleRuleBase>> rules;
 
@@ -503,7 +503,7 @@
         m_observerWrapper->observer().startRuleBody(m_observerWrapper->previousTokenStartOffset(block));
     }
 
-    consumeRuleList(block, RegularRuleList, [&rules](RawPtr<StyleRuleBase> rule) {
+    consumeRuleList(block, RegularRuleList, [&rules](StyleRuleBase* rule) {
         rules.append(rule);
     });
 
@@ -513,7 +513,7 @@
     return StyleRuleMedia::create(MediaQueryParser::parseMediaQuerySet(prelude), rules);
 }
 
-RawPtr<StyleRuleSupports> CSSParserImpl::consumeSupportsRule(CSSParserTokenRange prelude, CSSParserTokenRange block)
+StyleRuleSupports* CSSParserImpl::consumeSupportsRule(CSSParserTokenRange prelude, CSSParserTokenRange block)
 {
     CSSSupportsParser::SupportsResult supported = CSSSupportsParser::supportsCondition(prelude, *this);
     if (supported == CSSSupportsParser::Invalid)
@@ -526,7 +526,7 @@
     }
 
     HeapVector<Member<StyleRuleBase>> rules;
-    consumeRuleList(block, RegularRuleList, [&rules](RawPtr<StyleRuleBase> rule) {
+    consumeRuleList(block, RegularRuleList, [&rules](StyleRuleBase* rule) {
         rules.append(rule);
     });
 
@@ -536,7 +536,7 @@
     return StyleRuleSupports::create(prelude.serialize().stripWhiteSpace(), supported, rules);
 }
 
-RawPtr<StyleRuleViewport> CSSParserImpl::consumeViewportRule(CSSParserTokenRange prelude, CSSParserTokenRange block)
+StyleRuleViewport* CSSParserImpl::consumeViewportRule(CSSParserTokenRange prelude, CSSParserTokenRange block)
 {
     // Allow @viewport rules from UA stylesheets even if the feature is disabled.
     if (!RuntimeEnabledFeatures::cssViewportEnabled() && !isUASheetBehavior(m_context.mode()))
@@ -558,7 +558,7 @@
     return StyleRuleViewport::create(createStylePropertySet(m_parsedProperties, CSSViewportRuleMode));
 }
 
-RawPtr<StyleRuleFontFace> CSSParserImpl::consumeFontFaceRule(CSSParserTokenRange prelude, CSSParserTokenRange block)
+StyleRuleFontFace* CSSParserImpl::consumeFontFaceRule(CSSParserTokenRange prelude, CSSParserTokenRange block)
 {
     prelude.consumeWhitespace();
     if (!prelude.atEnd())
@@ -579,7 +579,7 @@
     return StyleRuleFontFace::create(createStylePropertySet(m_parsedProperties, m_context.mode()));
 }
 
-RawPtr<StyleRuleKeyframes> CSSParserImpl::consumeKeyframesRule(bool webkitPrefixed, CSSParserTokenRange prelude, CSSParserTokenRange block)
+StyleRuleKeyframes* CSSParserImpl::consumeKeyframesRule(bool webkitPrefixed, CSSParserTokenRange prelude, CSSParserTokenRange block)
 {
     prelude.consumeWhitespace();
     CSSParserTokenRange rangeCopy = prelude; // For inspector callbacks
@@ -605,16 +605,16 @@
         m_observerWrapper->observer().endRuleBody(m_observerWrapper->endOffset(block));
     }
 
-    RawPtr<StyleRuleKeyframes> keyframeRule = StyleRuleKeyframes::create();
-    consumeRuleList(block, KeyframesRuleList, [keyframeRule](RawPtr<StyleRuleBase> keyframe) {
-        keyframeRule->parserAppendKeyframe(toStyleRuleKeyframe(keyframe.get()));
+    StyleRuleKeyframes* keyframeRule = StyleRuleKeyframes::create();
+    consumeRuleList(block, KeyframesRuleList, [keyframeRule](StyleRuleBase* keyframe) {
+        keyframeRule->parserAppendKeyframe(toStyleRuleKeyframe(keyframe));
     });
     keyframeRule->setName(name);
     keyframeRule->setVendorPrefixed(webkitPrefixed);
-    return keyframeRule.release();
+    return keyframeRule;
 }
 
-RawPtr<StyleRulePage> CSSParserImpl::consumePageRule(CSSParserTokenRange prelude, CSSParserTokenRange block)
+StyleRulePage* CSSParserImpl::consumePageRule(CSSParserTokenRange prelude, CSSParserTokenRange block)
 {
     CSSSelectorList selectorList = parsePageSelector(prelude, m_styleSheet);
     if (!selectorList.isValid())
@@ -644,7 +644,7 @@
         CSSCustomIdentValue::create(ident.value())));
 }
 
-RawPtr<StyleRuleKeyframe> CSSParserImpl::consumeKeyframeStyleRule(CSSParserTokenRange prelude, CSSParserTokenRange block)
+StyleRuleKeyframe* CSSParserImpl::consumeKeyframeStyleRule(CSSParserTokenRange prelude, CSSParserTokenRange block)
 {
     OwnPtr<Vector<double>> keyList = consumeKeyframeKeyList(prelude);
     if (!keyList)
@@ -680,7 +680,7 @@
 }
 
 
-RawPtr<StyleRule> CSSParserImpl::consumeStyleRule(CSSParserTokenRange prelude, CSSParserTokenRange block)
+StyleRule* CSSParserImpl::consumeStyleRule(CSSParserTokenRange prelude, CSSParserTokenRange block)
 {
     CSSSelectorList selectorList = CSSSelectorParser::parseSelector(prelude, m_context, m_styleSheet);
     if (!selectorList.isValid())
@@ -727,7 +727,7 @@
         }
         case AtKeywordToken: {
             AllowedRulesType allowedRules = ruleType == StyleRule::Style && RuntimeEnabledFeatures::cssApplyAtRulesEnabled() ? ApplyRules : NoRules;
-            RawPtr<StyleRuleBase> rule = consumeAtRule(range, allowedRules);
+            StyleRuleBase* rule = consumeAtRule(range, allowedRules);
             ASSERT_UNUSED(rule, !rule);
             break;
         }
@@ -794,8 +794,8 @@
 
 void CSSParserImpl::consumeVariableValue(CSSParserTokenRange range, const AtomicString& variableName, bool important)
 {
-    if (RawPtr<CSSCustomPropertyDeclaration> value = CSSVariableParser::parseDeclarationValue(variableName, range))
-        m_parsedProperties.append(CSSProperty(CSSPropertyVariable, value.release(), important));
+    if (CSSCustomPropertyDeclaration* value = CSSVariableParser::parseDeclarationValue(variableName, range))
+        m_parsedProperties.append(CSSProperty(CSSPropertyVariable, value, important));
 }
 
 void CSSParserImpl::consumeDeclarationValue(CSSParserTokenRange range, CSSPropertyID unresolvedProperty, bool important, StyleRule::RuleType ruleType)
diff --git a/third_party/WebKit/Source/core/css/parser/CSSParserImpl.h b/third_party/WebKit/Source/core/css/parser/CSSParserImpl.h
index 71b8fb1..c89f290 100644
--- a/third_party/WebKit/Source/core/css/parser/CSSParserImpl.h
+++ b/third_party/WebKit/Source/core/css/parser/CSSParserImpl.h
@@ -57,13 +57,13 @@
 
     static bool parseValue(MutableStylePropertySet*, CSSPropertyID, const String&, bool important, const CSSParserContext&);
     static bool parseVariableValue(MutableStylePropertySet*, const AtomicString& propertyName, const String&, bool important, const CSSParserContext&);
-    static RawPtr<ImmutableStylePropertySet> parseInlineStyleDeclaration(const String&, Element*);
+    static ImmutableStylePropertySet* parseInlineStyleDeclaration(const String&, Element*);
     static bool parseDeclarationList(MutableStylePropertySet*, const String&, const CSSParserContext&);
-    static RawPtr<StyleRuleBase> parseRule(const String&, const CSSParserContext&, StyleSheetContents*, AllowedRulesType);
+    static StyleRuleBase* parseRule(const String&, const CSSParserContext&, StyleSheetContents*, AllowedRulesType);
     static void parseStyleSheet(const String&, const CSSParserContext&, StyleSheetContents*);
     static CSSSelectorList parsePageSelector(CSSParserTokenRange, StyleSheetContents*);
 
-    static RawPtr<ImmutableStylePropertySet> parseCustomPropertySet(CSSParserTokenRange);
+    static ImmutableStylePropertySet* parseCustomPropertySet(CSSParserTokenRange);
 
     static PassOwnPtr<Vector<double>> parseKeyframeKeyList(const String&);
 
@@ -84,23 +84,23 @@
     bool consumeRuleList(CSSParserTokenRange, RuleListType, T callback);
 
     // These two functions update the range they're given
-    RawPtr<StyleRuleBase> consumeAtRule(CSSParserTokenRange&, AllowedRulesType);
-    RawPtr<StyleRuleBase> consumeQualifiedRule(CSSParserTokenRange&, AllowedRulesType);
+    StyleRuleBase* consumeAtRule(CSSParserTokenRange&, AllowedRulesType);
+    StyleRuleBase* consumeQualifiedRule(CSSParserTokenRange&, AllowedRulesType);
 
-    static RawPtr<StyleRuleCharset> consumeCharsetRule(CSSParserTokenRange prelude);
-    RawPtr<StyleRuleImport> consumeImportRule(CSSParserTokenRange prelude);
-    RawPtr<StyleRuleNamespace> consumeNamespaceRule(CSSParserTokenRange prelude);
-    RawPtr<StyleRuleMedia> consumeMediaRule(CSSParserTokenRange prelude, CSSParserTokenRange block);
-    RawPtr<StyleRuleSupports> consumeSupportsRule(CSSParserTokenRange prelude, CSSParserTokenRange block);
-    RawPtr<StyleRuleViewport> consumeViewportRule(CSSParserTokenRange prelude, CSSParserTokenRange block);
-    RawPtr<StyleRuleFontFace> consumeFontFaceRule(CSSParserTokenRange prelude, CSSParserTokenRange block);
-    RawPtr<StyleRuleKeyframes> consumeKeyframesRule(bool webkitPrefixed, CSSParserTokenRange prelude, CSSParserTokenRange block);
-    RawPtr<StyleRulePage> consumePageRule(CSSParserTokenRange prelude, CSSParserTokenRange block);
+    static StyleRuleCharset* consumeCharsetRule(CSSParserTokenRange prelude);
+    StyleRuleImport* consumeImportRule(CSSParserTokenRange prelude);
+    StyleRuleNamespace* consumeNamespaceRule(CSSParserTokenRange prelude);
+    StyleRuleMedia* consumeMediaRule(CSSParserTokenRange prelude, CSSParserTokenRange block);
+    StyleRuleSupports* consumeSupportsRule(CSSParserTokenRange prelude, CSSParserTokenRange block);
+    StyleRuleViewport* consumeViewportRule(CSSParserTokenRange prelude, CSSParserTokenRange block);
+    StyleRuleFontFace* consumeFontFaceRule(CSSParserTokenRange prelude, CSSParserTokenRange block);
+    StyleRuleKeyframes* consumeKeyframesRule(bool webkitPrefixed, CSSParserTokenRange prelude, CSSParserTokenRange block);
+    StyleRulePage* consumePageRule(CSSParserTokenRange prelude, CSSParserTokenRange block);
     // Updates m_parsedProperties
     void consumeApplyRule(CSSParserTokenRange prelude);
 
-    RawPtr<StyleRuleKeyframe> consumeKeyframeStyleRule(CSSParserTokenRange prelude, CSSParserTokenRange block);
-    RawPtr<StyleRule> consumeStyleRule(CSSParserTokenRange prelude, CSSParserTokenRange block);
+    StyleRuleKeyframe* consumeKeyframeStyleRule(CSSParserTokenRange prelude, CSSParserTokenRange block);
+    StyleRule* consumeStyleRule(CSSParserTokenRange prelude, CSSParserTokenRange block);
 
     void consumeDeclarationList(CSSParserTokenRange, StyleRule::RuleType);
     void consumeDeclaration(CSSParserTokenRange, StyleRule::RuleType);
diff --git a/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.cpp b/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.cpp
index 3dc334d..51bf905 100644
--- a/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.cpp
+++ b/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.cpp
@@ -101,16 +101,16 @@
     return parseSuccess;
 }
 
-RawPtr<CSSValue> CSSPropertyParser::parseSingleValue(
+CSSValue* CSSPropertyParser::parseSingleValue(
     CSSPropertyID property, const CSSParserTokenRange& range, const CSSParserContext& context)
 {
     if (hasInvalidNumericValues(range))
         return nullptr;
     CSSPropertyParser parser(range, context, nullptr);
-    RawPtr<CSSValue> value = parser.parseSingleValue(property);
+    CSSValue* value = parser.parseSingleValue(property);
     if (!value || !parser.m_range.atEnd())
         return nullptr;
-    return value.release();
+    return value;
 }
 
 bool CSSPropertyParser::isValidNumericValue(double value)
@@ -132,9 +132,9 @@
         if (parseShorthand(unresolvedProperty, important))
             return true;
     } else {
-        if (RawPtr<CSSValue> parsedValue = parseSingleValue(unresolvedProperty)) {
+        if (CSSValue* parsedValue = parseSingleValue(unresolvedProperty)) {
             if (m_range.atEnd()) {
-                addProperty(propertyId, parsedValue.release(), important);
+                addProperty(propertyId, parsedValue, important);
                 return true;
             }
         }
@@ -142,8 +142,8 @@
 
     if (RuntimeEnabledFeatures::cssVariablesEnabled() && CSSVariableParser::containsValidVariableReferences(originalRange)) {
         // We don't expand the shorthand here because crazypants.
-        RawPtr<CSSVariableReferenceValue> variable = CSSVariableReferenceValue::create(CSSVariableData::create(originalRange));
-        addProperty(propertyId, variable.release(), important);
+        CSSVariableReferenceValue* variable = CSSVariableReferenceValue::create(CSSVariableData::create(originalRange));
+        addProperty(propertyId, variable, important);
         return true;
     }
 
@@ -266,7 +266,7 @@
     if (!rangeCopy.atEnd())
         return false;
 
-    RawPtr<CSSValue> value = nullptr;
+    CSSValue* value = nullptr;
     if (id == CSSValueInitial)
         value = cssValuePool().createExplicitInitialValue();
     else if (id == CSSValueInherit)
@@ -276,35 +276,35 @@
     else
         return false;
 
-    addExpandedPropertyForValue(resolveCSSPropertyID(unresolvedProperty), value.release(), important);
+    addExpandedPropertyForValue(resolveCSSPropertyID(unresolvedProperty), value, important);
     m_range = rangeCopy;
     return true;
 }
 
-static RawPtr<CSSValueList> consumeTransformOrigin(CSSParserTokenRange& range, CSSParserMode cssParserMode, UnitlessQuirk unitless)
+static CSSValueList* consumeTransformOrigin(CSSParserTokenRange& range, CSSParserMode cssParserMode, UnitlessQuirk unitless)
 {
-    RawPtr<CSSValue> resultX = nullptr;
-    RawPtr<CSSValue> resultY = nullptr;
+    CSSValue* resultX = nullptr;
+    CSSValue* resultY = nullptr;
     if (consumeOneOrTwoValuedPosition(range, cssParserMode, unitless, resultX, resultY)) {
-        RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
-        list->append(resultX.release());
-        list->append(resultY.release());
-        RawPtr<CSSValue> resultZ = consumeLength(range, cssParserMode, ValueRangeAll);
+        CSSValueList* list = CSSValueList::createSpaceSeparated();
+        list->append(resultX);
+        list->append(resultY);
+        CSSValue* resultZ = consumeLength(range, cssParserMode, ValueRangeAll);
         if (!resultZ)
             resultZ = cssValuePool().createValue(0, CSSPrimitiveValue::UnitType::Pixels);
-        list->append(resultZ.release());
-        return list.release();
+        list->append(resultZ);
+        return list;
     }
     return nullptr;
 }
 
 // Methods for consuming non-shorthand properties starts here.
-static RawPtr<CSSValue> consumeWillChange(CSSParserTokenRange& range)
+static CSSValue* consumeWillChange(CSSParserTokenRange& range)
 {
     if (range.peek().id() == CSSValueAuto)
         return consumeIdent(range);
 
-    RawPtr<CSSValueList> values = CSSValueList::createCommaSeparated();
+    CSSValueList* values = CSSValueList::createCommaSeparated();
     // Every comma-separated list of identifiers is a valid will-change value,
     // unless the list includes an explicitly disallowed identifier.
     while (true) {
@@ -344,10 +344,10 @@
             return nullptr;
     }
 
-    return values.release();
+    return values;
 }
 
-static RawPtr<CSSFontFeatureValue> consumeFontFeatureTag(CSSParserTokenRange& range)
+static CSSFontFeatureValue* consumeFontFeatureTag(CSSParserTokenRange& range)
 {
     // Feature tag name consists of 4-letter characters.
     static const unsigned tagNameLength = 4;
@@ -378,55 +378,55 @@
     return CSSFontFeatureValue::create(tag, tagValue);
 }
 
-static RawPtr<CSSValue> consumeFontFeatureSettings(CSSParserTokenRange& range)
+static CSSValue* consumeFontFeatureSettings(CSSParserTokenRange& range)
 {
     if (range.peek().id() == CSSValueNormal)
         return consumeIdent(range);
-    RawPtr<CSSValueList> settings = CSSValueList::createCommaSeparated();
+    CSSValueList* settings = CSSValueList::createCommaSeparated();
     do {
-        RawPtr<CSSFontFeatureValue> fontFeatureValue = consumeFontFeatureTag(range);
+        CSSFontFeatureValue* fontFeatureValue = consumeFontFeatureTag(range);
         if (!fontFeatureValue)
             return nullptr;
         settings->append(fontFeatureValue);
     } while (consumeCommaIncludingWhitespace(range));
-    return settings.release();
+    return settings;
 }
 
-static RawPtr<CSSValue> consumePage(CSSParserTokenRange& range)
+static CSSValue* consumePage(CSSParserTokenRange& range)
 {
     if (range.peek().id() == CSSValueAuto)
         return consumeIdent(range);
     return consumeCustomIdent(range);
 }
 
-static RawPtr<CSSValue> consumeQuotes(CSSParserTokenRange& range)
+static CSSValue* consumeQuotes(CSSParserTokenRange& range)
 {
     if (range.peek().id() == CSSValueNone)
         return consumeIdent(range);
-    RawPtr<CSSValueList> values = CSSValueList::createSpaceSeparated();
+    CSSValueList* values = CSSValueList::createSpaceSeparated();
     while (!range.atEnd()) {
-        RawPtr<CSSStringValue> parsedValue = consumeString(range);
+        CSSStringValue* parsedValue = consumeString(range);
         if (!parsedValue)
             return nullptr;
-        values->append(parsedValue.release());
+        values->append(parsedValue);
     }
     if (values->length() && values->length() % 2 == 0)
-        return values.release();
+        return values;
     return nullptr;
 }
 
-static RawPtr<CSSValue> consumeWebkitHighlight(CSSParserTokenRange& range)
+static CSSValue* consumeWebkitHighlight(CSSParserTokenRange& range)
 {
     if (range.peek().id() == CSSValueNone)
         return consumeIdent(range);
     return consumeString(range);
 }
 
-static RawPtr<CSSValue> consumeFontVariantLigatures(CSSParserTokenRange& range)
+static CSSValue* consumeFontVariantLigatures(CSSParserTokenRange& range)
 {
     if (range.peek().id() == CSSValueNormal)
         return consumeIdent(range);
-    RawPtr<CSSValueList> ligatureValues = CSSValueList::createSpaceSeparated();
+    CSSValueList* ligatureValues = CSSValueList::createSpaceSeparated();
     bool sawCommonLigaturesValue = false;
     bool sawDiscretionaryLigaturesValue = false;
     bool sawHistoricalLigaturesValue = false;
@@ -464,17 +464,17 @@
         ligatureValues->append(consumeIdent(range));
     } while (!range.atEnd());
 
-    return ligatureValues.release();
+    return ligatureValues;
 }
 
-static RawPtr<CSSPrimitiveValue> consumeFontVariant(CSSParserTokenRange& range)
+static CSSPrimitiveValue* consumeFontVariant(CSSParserTokenRange& range)
 {
     return consumeIdent<CSSValueNormal, CSSValueSmallCaps>(range);
 }
 
-static RawPtr<CSSValue> consumeFontVariantList(CSSParserTokenRange& range)
+static CSSValue* consumeFontVariantList(CSSParserTokenRange& range)
 {
-    RawPtr<CSSValueList> values = CSSValueList::createCommaSeparated();
+    CSSValueList* values = CSSValueList::createCommaSeparated();
     do {
         if (range.peek().id() == CSSValueAll) {
             // FIXME: CSSPropertyParser::parseFontVariant() implements
@@ -485,18 +485,18 @@
                 return nullptr;
             return consumeIdent(range);
         }
-        RawPtr<CSSPrimitiveValue> fontVariant = consumeFontVariant(range);
+        CSSPrimitiveValue* fontVariant = consumeFontVariant(range);
         if (fontVariant)
-            values->append(fontVariant.release());
+            values->append(fontVariant);
     } while (consumeCommaIncludingWhitespace(range));
 
     if (values->length())
-        return values.release();
+        return values;
 
     return nullptr;
 }
 
-static RawPtr<CSSPrimitiveValue> consumeFontWeight(CSSParserTokenRange& range)
+static CSSPrimitiveValue* consumeFontWeight(CSSParserTokenRange& range)
 {
     const CSSParserToken& token = range.peek();
     if (token.id() >= CSSValueNormal && token.id() <= CSSValueLighter)
@@ -527,7 +527,7 @@
     return builder.toString();
 }
 
-static RawPtr<CSSValue> consumeFamilyName(CSSParserTokenRange& range)
+static CSSValue* consumeFamilyName(CSSParserTokenRange& range)
 {
     if (range.peek().type() == StringToken)
         return cssValuePool().createFontFamilyValue(range.consumeIncludingWhitespace().value());
@@ -539,28 +539,31 @@
     return cssValuePool().createFontFamilyValue(familyName);
 }
 
-static RawPtr<CSSValue> consumeGenericFamily(CSSParserTokenRange& range)
+static CSSValue* consumeGenericFamily(CSSParserTokenRange& range)
 {
     return consumeIdentRange(range, CSSValueSerif, CSSValueWebkitBody);
 }
 
-static RawPtr<CSSValueList> consumeFontFamily(CSSParserTokenRange& range)
+static CSSValueList* consumeFontFamily(CSSParserTokenRange& range)
 {
-    RawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+    CSSValueList* list = CSSValueList::createCommaSeparated();
     do {
-        RawPtr<CSSValue> parsedValue = nullptr;
-        if ((parsedValue = consumeGenericFamily(range))) {
-            list->append(parsedValue);
-        } else if ((parsedValue = consumeFamilyName(range))) {
+        CSSValue* parsedValue = consumeGenericFamily(range);
+        if (parsedValue) {
             list->append(parsedValue);
         } else {
-            return nullptr;
+            parsedValue = consumeFamilyName(range);
+            if (parsedValue) {
+                list->append(parsedValue);
+            } else {
+                return nullptr;
+            }
         }
     } while (consumeCommaIncludingWhitespace(range));
-    return list.release();
+    return list;
 }
 
-static RawPtr<CSSValue> consumeSpacing(CSSParserTokenRange& range, CSSParserMode cssParserMode)
+static CSSValue* consumeSpacing(CSSParserTokenRange& range, CSSParserMode cssParserMode)
 {
     if (range.peek().id() == CSSValueNormal)
         return consumeIdent(range);
@@ -568,168 +571,172 @@
     return consumeLength(range, cssParserMode, ValueRangeAll, UnitlessQuirk::Allow);
 }
 
-static RawPtr<CSSValue> consumeTabSize(CSSParserTokenRange& range, CSSParserMode cssParserMode)
+static CSSValue* consumeTabSize(CSSParserTokenRange& range, CSSParserMode cssParserMode)
 {
-    RawPtr<CSSPrimitiveValue> parsedValue = consumeInteger(range, 0);
+    CSSPrimitiveValue* parsedValue = consumeInteger(range, 0);
     if (parsedValue)
         return parsedValue;
     return consumeLength(range, cssParserMode, ValueRangeNonNegative);
 }
 
-static RawPtr<CSSValue> consumeFontSize(CSSParserTokenRange& range, CSSParserMode cssParserMode, UnitlessQuirk unitless = UnitlessQuirk::Forbid)
+static CSSValue* consumeFontSize(CSSParserTokenRange& range, CSSParserMode cssParserMode, UnitlessQuirk unitless = UnitlessQuirk::Forbid)
 {
     if (range.peek().id() >= CSSValueXxSmall && range.peek().id() <= CSSValueLarger)
         return consumeIdent(range);
     return consumeLengthOrPercent(range, cssParserMode, ValueRangeNonNegative, unitless);
 }
 
-static RawPtr<CSSPrimitiveValue> consumeLineHeight(CSSParserTokenRange& range, CSSParserMode cssParserMode)
+static CSSPrimitiveValue* consumeLineHeight(CSSParserTokenRange& range, CSSParserMode cssParserMode)
 {
     if (range.peek().id() == CSSValueNormal)
         return consumeIdent(range);
 
-    RawPtr<CSSPrimitiveValue> lineHeight = consumeNumber(range, ValueRangeNonNegative);
+    CSSPrimitiveValue* lineHeight = consumeNumber(range, ValueRangeNonNegative);
     if (lineHeight)
         return lineHeight;
     return consumeLengthOrPercent(range, cssParserMode, ValueRangeNonNegative);
 }
 
-static RawPtr<CSSValueList> consumeRotation(CSSParserTokenRange& range)
+static CSSValueList* consumeRotation(CSSParserTokenRange& range)
 {
     ASSERT(RuntimeEnabledFeatures::cssIndependentTransformPropertiesEnabled());
-    RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    CSSValueList* list = CSSValueList::createSpaceSeparated();
 
-    RawPtr<CSSValue> rotation = consumeAngle(range);
+    CSSValue* rotation = consumeAngle(range);
     if (!rotation)
         return nullptr;
-    list->append(rotation.release());
+    list->append(rotation);
 
     if (range.atEnd())
-        return list.release();
+        return list;
 
     for (unsigned i = 0; i < 3; i++) { // 3 dimensions of rotation
-        RawPtr<CSSValue> dimension = consumeNumber(range, ValueRangeAll);
+        CSSValue* dimension = consumeNumber(range, ValueRangeAll);
         if (!dimension)
             return nullptr;
-        list->append(dimension.release());
+        list->append(dimension);
     }
 
-    return list.release();
+    return list;
 }
 
-static RawPtr<CSSValueList> consumeScale(CSSParserTokenRange& range, CSSParserMode cssParserMode)
+static CSSValueList* consumeScale(CSSParserTokenRange& range, CSSParserMode cssParserMode)
 {
     ASSERT(RuntimeEnabledFeatures::cssIndependentTransformPropertiesEnabled());
 
-    RawPtr<CSSValue> scale = consumeNumber(range, ValueRangeAll);
+    CSSValue* scale = consumeNumber(range, ValueRangeAll);
     if (!scale)
         return nullptr;
-    RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
-    list->append(scale.release());
-    if ((scale = consumeNumber(range, ValueRangeAll))) {
-        list->append(scale.release());
-        if ((scale = consumeNumber(range, ValueRangeAll)))
-            list->append(scale.release());
+    CSSValueList* list = CSSValueList::createSpaceSeparated();
+    list->append(scale);
+    scale = consumeNumber(range, ValueRangeAll);
+    if (scale) {
+        list->append(scale);
+        scale = consumeNumber(range, ValueRangeAll);
+        if (scale)
+            list->append(scale);
     }
 
-    return list.release();
+    return list;
 }
 
-static RawPtr<CSSValueList> consumeTranslate(CSSParserTokenRange& range, CSSParserMode cssParserMode)
+static CSSValueList* consumeTranslate(CSSParserTokenRange& range, CSSParserMode cssParserMode)
 {
     ASSERT(RuntimeEnabledFeatures::cssIndependentTransformPropertiesEnabled());
-    RawPtr<CSSValue> translate = consumeLengthOrPercent(range, cssParserMode, ValueRangeAll);
+    CSSValue* translate = consumeLengthOrPercent(range, cssParserMode, ValueRangeAll);
     if (!translate)
         return nullptr;
-    RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
-    list->append(translate.release());
-    if ((translate = consumeLengthOrPercent(range, cssParserMode, ValueRangeAll))) {
-        list->append(translate.release());
-        if ((translate = consumeLength(range, cssParserMode, ValueRangeAll)))
-            list->append(translate.release());
+    CSSValueList* list = CSSValueList::createSpaceSeparated();
+    list->append(translate);
+    translate = consumeLengthOrPercent(range, cssParserMode, ValueRangeAll);
+    if (translate) {
+        list->append(translate);
+        translate = consumeLength(range, cssParserMode, ValueRangeAll);
+        if (translate)
+            list->append(translate);
     }
 
-    return list.release();
+    return list;
 }
 
-static RawPtr<CSSValue> consumeCounter(CSSParserTokenRange& range, CSSParserMode cssParserMode, int defaultValue)
+static CSSValue* consumeCounter(CSSParserTokenRange& range, CSSParserMode cssParserMode, int defaultValue)
 {
     if (range.peek().id() == CSSValueNone)
         return consumeIdent(range);
 
-    RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    CSSValueList* list = CSSValueList::createSpaceSeparated();
     do {
-        RawPtr<CSSCustomIdentValue> counterName = consumeCustomIdent(range);
+        CSSCustomIdentValue* counterName = consumeCustomIdent(range);
         if (!counterName)
             return nullptr;
         int i = defaultValue;
-        if (RawPtr<CSSPrimitiveValue> counterValue = consumeInteger(range))
+        if (CSSPrimitiveValue* counterValue = consumeInteger(range))
             i = clampTo<int>(counterValue->getDoubleValue());
-        list->append(CSSValuePair::create(counterName.release(),
+        list->append(CSSValuePair::create(counterName,
             cssValuePool().createValue(i, CSSPrimitiveValue::UnitType::Integer),
             CSSValuePair::DropIdenticalValues));
     } while (!range.atEnd());
-    return list.release();
+    return list;
 }
 
-static RawPtr<CSSValue> consumePageSize(CSSParserTokenRange& range)
+static CSSValue* consumePageSize(CSSParserTokenRange& range)
 {
     return consumeIdent<CSSValueA3, CSSValueA4, CSSValueA5, CSSValueB4, CSSValueB5, CSSValueLedger, CSSValueLegal, CSSValueLetter>(range);
 }
 
-static RawPtr<CSSValueList> consumeSize(CSSParserTokenRange& range, CSSParserMode cssParserMode)
+static CSSValueList* consumeSize(CSSParserTokenRange& range, CSSParserMode cssParserMode)
 {
-    RawPtr<CSSValueList> result = CSSValueList::createSpaceSeparated();
+    CSSValueList* result = CSSValueList::createSpaceSeparated();
 
     if (range.peek().id() == CSSValueAuto) {
         result->append(consumeIdent(range));
-        return result.release();
+        return result;
     }
 
-    if (RawPtr<CSSValue> width = consumeLength(range, cssParserMode, ValueRangeNonNegative)) {
-        RawPtr<CSSValue> height = consumeLength(range, cssParserMode, ValueRangeNonNegative);
-        result->append(width.release());
+    if (CSSValue* width = consumeLength(range, cssParserMode, ValueRangeNonNegative)) {
+        CSSValue* height = consumeLength(range, cssParserMode, ValueRangeNonNegative);
+        result->append(width);
         if (height)
-            result->append(height.release());
-        return result.release();
+            result->append(height);
+        return result;
     }
 
-    RawPtr<CSSValue> pageSize = consumePageSize(range);
-    RawPtr<CSSValue> orientation = consumeIdent<CSSValuePortrait, CSSValueLandscape>(range);
+    CSSValue* pageSize = consumePageSize(range);
+    CSSValue* orientation = consumeIdent<CSSValuePortrait, CSSValueLandscape>(range);
     if (!pageSize)
         pageSize = consumePageSize(range);
 
     if (!orientation && !pageSize)
         return nullptr;
     if (pageSize)
-        result->append(pageSize.release());
+        result->append(pageSize);
     if (orientation)
-        result->append(orientation.release());
-    return result.release();
+        result->append(orientation);
+    return result;
 }
 
-static RawPtr<CSSValue> consumeSnapHeight(CSSParserTokenRange& range, CSSParserMode cssParserMode)
+static CSSValue* consumeSnapHeight(CSSParserTokenRange& range, CSSParserMode cssParserMode)
 {
-    RawPtr<CSSPrimitiveValue> unit = consumeLength(range, cssParserMode, ValueRangeNonNegative);
+    CSSPrimitiveValue* unit = consumeLength(range, cssParserMode, ValueRangeNonNegative);
     if (!unit)
         return nullptr;
-    RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
-    list->append(unit.release());
+    CSSValueList* list = CSSValueList::createSpaceSeparated();
+    list->append(unit);
 
-    if (RawPtr<CSSPrimitiveValue> position = consumePositiveInteger(range)) {
+    if (CSSPrimitiveValue* position = consumePositiveInteger(range)) {
         if (position->getIntValue() > 100)
             return nullptr;
-        list->append(position.release());
+        list->append(position);
     }
 
-    return list.release();
+    return list;
 }
 
-static RawPtr<CSSValue> consumeTextIndent(CSSParserTokenRange& range, CSSParserMode cssParserMode)
+static CSSValue* consumeTextIndent(CSSParserTokenRange& range, CSSParserMode cssParserMode)
 {
     // [ <length> | <percentage> ] && hanging? && each-line?
     // Keywords only allowed when css3Text is enabled.
-    RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    CSSValueList* list = CSSValueList::createSpaceSeparated();
 
     bool hasLengthOrPercentage = false;
     bool hasEachLine = false;
@@ -737,8 +744,8 @@
 
     do {
         if (!hasLengthOrPercentage) {
-            if (RawPtr<CSSValue> textIndent = consumeLengthOrPercent(range, cssParserMode, ValueRangeAll, UnitlessQuirk::Allow)) {
-                list->append(textIndent.release());
+            if (CSSValue* textIndent = consumeLengthOrPercent(range, cssParserMode, ValueRangeAll, UnitlessQuirk::Allow)) {
+                list->append(textIndent);
                 hasLengthOrPercentage = true;
                 continue;
             }
@@ -763,7 +770,7 @@
     if (!hasLengthOrPercentage)
         return nullptr;
 
-    return list.release();
+    return list;
 }
 
 static bool validWidthOrHeightKeyword(CSSValueID id, const CSSParserContext& context)
@@ -793,35 +800,35 @@
     return false;
 }
 
-static RawPtr<CSSValue> consumeMaxWidthOrHeight(CSSParserTokenRange& range, const CSSParserContext& context, UnitlessQuirk unitless = UnitlessQuirk::Forbid)
+static CSSValue* consumeMaxWidthOrHeight(CSSParserTokenRange& range, const CSSParserContext& context, UnitlessQuirk unitless = UnitlessQuirk::Forbid)
 {
     if (range.peek().id() == CSSValueNone || validWidthOrHeightKeyword(range.peek().id(), context))
         return consumeIdent(range);
     return consumeLengthOrPercent(range, context.mode(), ValueRangeNonNegative, unitless);
 }
 
-static RawPtr<CSSValue> consumeWidthOrHeight(CSSParserTokenRange& range, const CSSParserContext& context, UnitlessQuirk unitless = UnitlessQuirk::Forbid)
+static CSSValue* consumeWidthOrHeight(CSSParserTokenRange& range, const CSSParserContext& context, UnitlessQuirk unitless = UnitlessQuirk::Forbid)
 {
     if (range.peek().id() == CSSValueAuto || validWidthOrHeightKeyword(range.peek().id(), context))
         return consumeIdent(range);
     return consumeLengthOrPercent(range, context.mode(), ValueRangeNonNegative, unitless);
 }
 
-static RawPtr<CSSValue> consumeMarginOrOffset(CSSParserTokenRange& range, CSSParserMode cssParserMode, UnitlessQuirk unitless)
+static CSSValue* consumeMarginOrOffset(CSSParserTokenRange& range, CSSParserMode cssParserMode, UnitlessQuirk unitless)
 {
     if (range.peek().id() == CSSValueAuto)
         return consumeIdent(range);
     return consumeLengthOrPercent(range, cssParserMode, ValueRangeAll, unitless);
 }
 
-static RawPtr<CSSPrimitiveValue> consumeClipComponent(CSSParserTokenRange& range, CSSParserMode cssParserMode)
+static CSSPrimitiveValue* consumeClipComponent(CSSParserTokenRange& range, CSSParserMode cssParserMode)
 {
     if (range.peek().id() == CSSValueAuto)
         return consumeIdent(range);
     return consumeLength(range, cssParserMode, ValueRangeAll, UnitlessQuirk::Allow);
 }
 
-static RawPtr<CSSValue> consumeClip(CSSParserTokenRange& range, CSSParserMode cssParserMode)
+static CSSValue* consumeClip(CSSParserTokenRange& range, CSSParserMode cssParserMode)
 {
     if (range.peek().id() == CSSValueAuto)
         return consumeIdent(range);
@@ -831,23 +838,23 @@
 
     CSSParserTokenRange args = consumeFunction(range);
     // rect(t, r, b, l) || rect(t r b l)
-    RawPtr<CSSPrimitiveValue> top = consumeClipComponent(args, cssParserMode);
+    CSSPrimitiveValue* top = consumeClipComponent(args, cssParserMode);
     if (!top)
         return nullptr;
     bool needsComma = consumeCommaIncludingWhitespace(args);
-    RawPtr<CSSPrimitiveValue> right = consumeClipComponent(args, cssParserMode);
+    CSSPrimitiveValue* right = consumeClipComponent(args, cssParserMode);
     if (!right || (needsComma && !consumeCommaIncludingWhitespace(args)))
         return nullptr;
-    RawPtr<CSSPrimitiveValue> bottom = consumeClipComponent(args, cssParserMode);
+    CSSPrimitiveValue* bottom = consumeClipComponent(args, cssParserMode);
     if (!bottom || (needsComma && !consumeCommaIncludingWhitespace(args)))
         return nullptr;
-    RawPtr<CSSPrimitiveValue> left = consumeClipComponent(args, cssParserMode);
+    CSSPrimitiveValue* left = consumeClipComponent(args, cssParserMode);
     if (!left || !args.atEnd())
         return nullptr;
-    return CSSQuadValue::create(top.release(), right.release(), bottom.release(), left.release(), CSSQuadValue::SerializeAsRect);
+    return CSSQuadValue::create(top, right, bottom, left, CSSQuadValue::SerializeAsRect);
 }
 
-static bool consumePan(CSSParserTokenRange& range, RawPtr<CSSValue>& panX, RawPtr<CSSValue>& panY)
+static bool consumePan(CSSParserTokenRange& range, CSSValue*& panX, CSSValue*& panY)
 {
     CSSValueID id = range.peek().id();
     if ((id == CSSValuePanX || id == CSSValuePanRight || id == CSSValuePanLeft) && !panX) {
@@ -864,82 +871,82 @@
     return true;
 }
 
-static RawPtr<CSSValue> consumeTouchAction(CSSParserTokenRange& range)
+static CSSValue* consumeTouchAction(CSSParserTokenRange& range)
 {
-    RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    CSSValueList* list = CSSValueList::createSpaceSeparated();
     CSSValueID id = range.peek().id();
     if (id == CSSValueAuto || id == CSSValueNone || id == CSSValueManipulation) {
         list->append(consumeIdent(range));
-        return list.release();
+        return list;
     }
 
-    RawPtr<CSSValue> panX = nullptr;
-    RawPtr<CSSValue> panY = nullptr;
+    CSSValue* panX = nullptr;
+    CSSValue* panY = nullptr;
     if (!consumePan(range, panX, panY))
         return nullptr;
     if (!range.atEnd() && !consumePan(range, panX, panY))
         return nullptr;
 
     if (panX)
-        list->append(panX.release());
+        list->append(panX);
     if (panY)
-        list->append(panY.release());
-    return list.release();
+        list->append(panY);
+    return list;
 }
 
-static RawPtr<CSSPrimitiveValue> consumeLineClamp(CSSParserTokenRange& range)
+static CSSPrimitiveValue* consumeLineClamp(CSSParserTokenRange& range)
 {
     if (range.peek().type() != PercentageToken && range.peek().type() != NumberToken)
         return nullptr;
-    RawPtr<CSSPrimitiveValue> clampValue = consumePercent(range, ValueRangeNonNegative);
+    CSSPrimitiveValue* clampValue = consumePercent(range, ValueRangeNonNegative);
     if (clampValue)
         return clampValue;
     // When specifying number of lines, don't allow 0 as a valid value.
     return consumePositiveInteger(range);
 }
 
-static RawPtr<CSSValue> consumeLocale(CSSParserTokenRange& range)
+static CSSValue* consumeLocale(CSSParserTokenRange& range)
 {
     if (range.peek().id() == CSSValueAuto)
         return consumeIdent(range);
     return consumeString(range);
 }
 
-static RawPtr<CSSValue> consumeColumnWidth(CSSParserTokenRange& range)
+static CSSValue* consumeColumnWidth(CSSParserTokenRange& range)
 {
     if (range.peek().id() == CSSValueAuto)
         return consumeIdent(range);
     // Always parse lengths in strict mode here, since it would be ambiguous otherwise when used in
     // the 'columns' shorthand property.
-    RawPtr<CSSPrimitiveValue> columnWidth = consumeLength(range, HTMLStandardMode, ValueRangeNonNegative);
+    CSSPrimitiveValue* columnWidth = consumeLength(range, HTMLStandardMode, ValueRangeNonNegative);
     if (!columnWidth || (!columnWidth->isCalculated() && columnWidth->getDoubleValue() == 0))
         return nullptr;
-    return columnWidth.release();
+    return columnWidth;
 }
 
-static RawPtr<CSSValue> consumeColumnCount(CSSParserTokenRange& range)
+static CSSValue* consumeColumnCount(CSSParserTokenRange& range)
 {
     if (range.peek().id() == CSSValueAuto)
         return consumeIdent(range);
     return consumePositiveInteger(range);
 }
 
-static RawPtr<CSSValue> consumeColumnGap(CSSParserTokenRange& range, CSSParserMode cssParserMode)
+static CSSValue* consumeColumnGap(CSSParserTokenRange& range, CSSParserMode cssParserMode)
 {
     if (range.peek().id() == CSSValueNormal)
         return consumeIdent(range);
     return consumeLength(range, cssParserMode, ValueRangeNonNegative);
 }
 
-static RawPtr<CSSValue> consumeColumnSpan(CSSParserTokenRange& range, CSSParserMode cssParserMode)
+static CSSValue* consumeColumnSpan(CSSParserTokenRange& range, CSSParserMode cssParserMode)
 {
     return consumeIdent<CSSValueAll, CSSValueNone>(range);
 }
 
-static RawPtr<CSSValue> consumeZoom(CSSParserTokenRange& range, const CSSParserContext& context)
+static CSSValue* consumeZoom(CSSParserTokenRange& range, const CSSParserContext& context)
 {
     const CSSParserToken& token = range.peek();
-    RawPtr<CSSPrimitiveValue> zoom = nullptr;
+    CSSPrimitiveValue* zoom = nullptr;
     if (token.type() == IdentToken) {
         zoom = consumeIdent<CSSValueNormal, CSSValueReset, CSSValueDocument>(range);
     } else {
@@ -952,17 +959,17 @@
             || (token.type() == NumberToken && zoom->getDoubleValue() == 1)
             || (token.type() == PercentageToken && zoom->getDoubleValue() == 100)))
         context.useCounter()->count(UseCounter::CSSZoomNotEqualToOne);
-    return zoom.release();
+    return zoom;
 }
 
-static RawPtr<CSSValue> consumeAnimationIterationCount(CSSParserTokenRange& range)
+static CSSValue* consumeAnimationIterationCount(CSSParserTokenRange& range)
 {
     if (range.peek().id() == CSSValueInfinite)
         return consumeIdent(range);
     return consumeNumber(range, ValueRangeNonNegative);
 }
 
-static RawPtr<CSSValue> consumeAnimationName(CSSParserTokenRange& range, const CSSParserContext& context, bool allowQuotedName)
+static CSSValue* consumeAnimationName(CSSParserTokenRange& range, const CSSParserContext& context, bool allowQuotedName)
 {
     if (range.peek().id() == CSSValueNone)
         return consumeIdent(range);
@@ -981,7 +988,7 @@
     return consumeCustomIdent(range);
 }
 
-static RawPtr<CSSValue> consumeTransitionProperty(CSSParserTokenRange& range)
+static CSSValue* consumeTransitionProperty(CSSParserTokenRange& range)
 {
     const CSSParserToken& token = range.peek();
     if (token.type() != IdentToken)
@@ -997,13 +1004,13 @@
     return consumeCustomIdent(range);
 }
 
-static RawPtr<CSSValue> consumeSteps(CSSParserTokenRange& range)
+static CSSValue* consumeSteps(CSSParserTokenRange& range)
 {
     ASSERT(range.peek().functionId() == CSSValueSteps);
     CSSParserTokenRange rangeCopy = range;
     CSSParserTokenRange args = consumeFunction(rangeCopy);
 
-    RawPtr<CSSPrimitiveValue> steps = consumePositiveInteger(args);
+    CSSPrimitiveValue* steps = consumePositiveInteger(args);
     if (!steps)
         return nullptr;
 
@@ -1033,7 +1040,7 @@
     return CSSStepsTimingFunctionValue::create(steps->getIntValue(), position);
 }
 
-static RawPtr<CSSValue> consumeCubicBezier(CSSParserTokenRange& range)
+static CSSValue* consumeCubicBezier(CSSParserTokenRange& range)
 {
     ASSERT(range.peek().functionId() == CSSValueCubicBezier);
     CSSParserTokenRange rangeCopy = range;
@@ -1057,7 +1064,7 @@
     return nullptr;
 }
 
-static RawPtr<CSSValue> consumeAnimationTimingFunction(CSSParserTokenRange& range)
+static CSSValue* consumeAnimationTimingFunction(CSSParserTokenRange& range)
 {
     CSSValueID id = range.peek().id();
     if (id == CSSValueEase || id == CSSValueLinear || id == CSSValueEaseIn
@@ -1073,7 +1080,7 @@
     return nullptr;
 }
 
-static RawPtr<CSSValue> consumeAnimationValue(CSSPropertyID property, CSSParserTokenRange& range, const CSSParserContext& context, bool useLegacyParsing)
+static CSSValue* consumeAnimationValue(CSSPropertyID property, CSSParserTokenRange& range, const CSSParserContext& context, bool useLegacyParsing)
 {
     switch (property) {
     case CSSPropertyAnimationDelay:
@@ -1115,25 +1122,25 @@
     return true;
 }
 
-static RawPtr<CSSValueList> consumeAnimationPropertyList(CSSPropertyID property, CSSParserTokenRange& range, const CSSParserContext& context, bool useLegacyParsing)
+static CSSValueList* consumeAnimationPropertyList(CSSPropertyID property, CSSParserTokenRange& range, const CSSParserContext& context, bool useLegacyParsing)
 {
-    RawPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+    CSSValueList* list = CSSValueList::createCommaSeparated();
     do {
-        RawPtr<CSSValue> value = consumeAnimationValue(property, range, context, useLegacyParsing);
+        CSSValue* value = consumeAnimationValue(property, range, context, useLegacyParsing);
         if (!value)
             return nullptr;
-        list->append(value.release());
+        list->append(value);
     } while (consumeCommaIncludingWhitespace(range));
     if (!isValidAnimationPropertyList(property, *list))
         return nullptr;
     ASSERT(list->length());
-    return list.release();
+    return list;
 }
 
 bool CSSPropertyParser::consumeAnimationShorthand(const StylePropertyShorthand& shorthand, bool useLegacyParsing, bool important)
 {
     const unsigned longhandCount = shorthand.length();
-    RawPtr<CSSValueList> longhands[8];
+    CSSValueList* longhands[8];
     ASSERT(longhandCount <= 8);
     for (size_t i = 0; i < longhandCount; ++i)
         longhands[i] = CSSValueList::createCommaSeparated();
@@ -1146,10 +1153,10 @@
                 if (parsedLonghand[i])
                     continue;
 
-                if (RawPtr<CSSValue> value = consumeAnimationValue(shorthand.properties()[i], m_range, m_context, useLegacyParsing)) {
+                if (CSSValue* value = consumeAnimationValue(shorthand.properties()[i], m_range, m_context, useLegacyParsing)) {
                     parsedLonghand[i] = true;
                     foundProperty = true;
-                    longhands[i]->append(value.release());
+                    longhands[i]->append(value);
                     break;
                 }
             }
@@ -1171,12 +1178,12 @@
     }
 
     for (size_t i = 0; i < longhandCount; ++i)
-        addProperty(shorthand.properties()[i], longhands[i].release(), important);
+        addProperty(shorthand.properties()[i], longhands[i], important);
 
     return m_range.atEnd();
 }
 
-static RawPtr<CSSValue> consumeWidowsOrOrphans(CSSParserTokenRange& range)
+static CSSValue* consumeWidowsOrOrphans(CSSParserTokenRange& range)
 {
     // Support for auto is non-standard and for backwards compatibility.
     if (range.peek().id() == CSSValueAuto)
@@ -1184,17 +1191,17 @@
     return consumePositiveInteger(range);
 }
 
-static RawPtr<CSSValue> consumeZIndex(CSSParserTokenRange& range)
+static CSSValue* consumeZIndex(CSSParserTokenRange& range)
 {
     if (range.peek().id() == CSSValueAuto)
         return consumeIdent(range);
     return consumeInteger(range);
 }
 
-static RawPtr<CSSShadowValue> parseSingleShadow(CSSParserTokenRange& range, CSSParserMode cssParserMode, bool allowInset, bool allowSpread)
+static CSSShadowValue* parseSingleShadow(CSSParserTokenRange& range, CSSParserMode cssParserMode, bool allowInset, bool allowSpread)
 {
-    RawPtr<CSSPrimitiveValue> style = nullptr;
-    RawPtr<CSSValue> color = nullptr;
+    CSSPrimitiveValue* style = nullptr;
+    CSSValue* color = nullptr;
 
     if (range.atEnd())
         return nullptr;
@@ -1205,16 +1212,16 @@
     }
     color = consumeColor(range, cssParserMode);
 
-    RawPtr<CSSPrimitiveValue> horizontalOffset = consumeLength(range, cssParserMode, ValueRangeAll);
+    CSSPrimitiveValue* horizontalOffset = consumeLength(range, cssParserMode, ValueRangeAll);
     if (!horizontalOffset)
         return nullptr;
 
-    RawPtr<CSSPrimitiveValue> verticalOffset = consumeLength(range, cssParserMode, ValueRangeAll);
+    CSSPrimitiveValue* verticalOffset = consumeLength(range, cssParserMode, ValueRangeAll);
     if (!verticalOffset)
         return nullptr;
 
-    RawPtr<CSSPrimitiveValue> blurRadius = consumeLength(range, cssParserMode, ValueRangeAll);
-    RawPtr<CSSPrimitiveValue> spreadDistance = nullptr;
+    CSSPrimitiveValue* blurRadius = consumeLength(range, cssParserMode, ValueRangeAll);
+    CSSPrimitiveValue* spreadDistance = nullptr;
     if (blurRadius) {
         // Blur radius must be non-negative.
         if (blurRadius->getDoubleValue() < 0)
@@ -1232,40 +1239,40 @@
             style = consumeIdent(range);
         }
     }
-    return CSSShadowValue::create(horizontalOffset.release(), verticalOffset.release(), blurRadius.release(),
-        spreadDistance.release(), style.release(), color.release());
+    return CSSShadowValue::create(horizontalOffset, verticalOffset, blurRadius,
+        spreadDistance, style, color);
 }
 
-static RawPtr<CSSValue> consumeShadow(CSSParserTokenRange& range, CSSParserMode cssParserMode, bool isBoxShadowProperty)
+static CSSValue* consumeShadow(CSSParserTokenRange& range, CSSParserMode cssParserMode, bool isBoxShadowProperty)
 {
     if (range.peek().id() == CSSValueNone)
         return consumeIdent(range);
 
-    RawPtr<CSSValueList> shadowValueList = CSSValueList::createCommaSeparated();
+    CSSValueList* shadowValueList = CSSValueList::createCommaSeparated();
     do {
-        if (RawPtr<CSSShadowValue> shadowValue = parseSingleShadow(range, cssParserMode, isBoxShadowProperty, isBoxShadowProperty))
-            shadowValueList->append(shadowValue.release());
+        if (CSSShadowValue* shadowValue = parseSingleShadow(range, cssParserMode, isBoxShadowProperty, isBoxShadowProperty))
+            shadowValueList->append(shadowValue);
         else
             return nullptr;
     } while (consumeCommaIncludingWhitespace(range));
     return shadowValueList;
 }
 
-static RawPtr<CSSFunctionValue> consumeFilterFunction(CSSParserTokenRange& range, CSSParserMode cssParserMode)
+static CSSFunctionValue* consumeFilterFunction(CSSParserTokenRange& range, CSSParserMode cssParserMode)
 {
     CSSValueID filterType = range.peek().functionId();
     if (filterType < CSSValueInvert || filterType > CSSValueDropShadow)
         return nullptr;
     CSSParserTokenRange args = consumeFunction(range);
-    RawPtr<CSSFunctionValue> filterValue = CSSFunctionValue::create(filterType);
-    RawPtr<CSSValue> parsedValue = nullptr;
+    CSSFunctionValue* filterValue = CSSFunctionValue::create(filterType);
+    CSSValue* parsedValue = nullptr;
 
     if (filterType == CSSValueDropShadow) {
         parsedValue = parseSingleShadow(args, cssParserMode, false, false);
     } else {
         // TODO(timloh): Add UseCounters for empty filter arguments.
         if (args.atEnd())
-            return filterValue.release();
+            return filterValue;
         if (filterType == CSSValueBrightness) {
             // FIXME (crbug.com/397061): Support calc expressions like calc(10% + 0.5)
             parsedValue = consumePercent(args, ValueRangeAll);
@@ -1281,27 +1288,27 @@
             if (!parsedValue)
                 parsedValue = consumeNumber(args, ValueRangeNonNegative);
             if (parsedValue && filterType != CSSValueSaturate && filterType != CSSValueContrast) {
-                double maxAllowed = toCSSPrimitiveValue(parsedValue.get())->isPercentage() ? 100.0 : 1.0;
-                if (toCSSPrimitiveValue(parsedValue.get())->getDoubleValue() > maxAllowed)
+                double maxAllowed = toCSSPrimitiveValue(parsedValue)->isPercentage() ? 100.0 : 1.0;
+                if (toCSSPrimitiveValue(parsedValue)->getDoubleValue() > maxAllowed)
                     return nullptr;
             }
         }
     }
     if (!parsedValue || !args.atEnd())
         return nullptr;
-    filterValue->append(parsedValue.release());
-    return filterValue.release();
+    filterValue->append(parsedValue);
+    return filterValue;
 }
 
-static RawPtr<CSSValue> consumeFilter(CSSParserTokenRange& range, CSSParserMode cssParserMode)
+static CSSValue* consumeFilter(CSSParserTokenRange& range, CSSParserMode cssParserMode)
 {
     if (range.peek().id() == CSSValueNone)
         return consumeIdent(range);
 
-    RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    CSSValueList* list = CSSValueList::createSpaceSeparated();
     do {
         String url = consumeUrl(range);
-        RawPtr<CSSFunctionValue> filterValue = nullptr;
+        CSSFunctionValue* filterValue = nullptr;
         if (!url.isNull()) {
             filterValue = CSSFunctionValue::create(CSSValueUrl);
             filterValue->append(CSSSVGDocumentValue::create(url));
@@ -1310,55 +1317,59 @@
             if (!filterValue)
                 return nullptr;
         }
-        list->append(filterValue.release());
+        list->append(filterValue);
     } while (!range.atEnd());
-    return list.release();
+    return list;
 }
 
-static RawPtr<CSSValue> consumeTextDecorationLine(CSSParserTokenRange& range)
+static CSSValue* consumeTextDecorationLine(CSSParserTokenRange& range)
 {
     CSSValueID id = range.peek().id();
     if (id == CSSValueNone)
         return consumeIdent(range);
 
-    RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
-    RawPtr<CSSPrimitiveValue> ident = nullptr;
-    while ((ident = consumeIdent<CSSValueBlink, CSSValueUnderline, CSSValueOverline, CSSValueLineThrough>(range))) {
-        if (list->hasValue(ident.get()))
+    CSSValueList* list = CSSValueList::createSpaceSeparated();
+    while (true) {
+        CSSPrimitiveValue* ident = consumeIdent<CSSValueBlink, CSSValueUnderline, CSSValueOverline, CSSValueLineThrough>(range);
+        if (!ident)
+            break;
+        if (list->hasValue(ident))
             return nullptr;
-        list->append(ident.release());
+        list->append(ident);
     }
 
     if (!list->length())
         return nullptr;
-    return list.release();
+    return list;
 }
 
 // none | strict | [ layout || style || paint ]
-static RawPtr<CSSValue> consumeContain(CSSParserTokenRange& range)
+static CSSValue* consumeContain(CSSParserTokenRange& range)
 {
     CSSValueID id = range.peek().id();
     if (id == CSSValueNone)
         return consumeIdent(range);
 
-    RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    CSSValueList* list = CSSValueList::createSpaceSeparated();
     if (id == CSSValueStrict) {
         list->append(consumeIdent(range));
-        return list.release();
+        return list;
     }
-    RawPtr<CSSPrimitiveValue> ident = nullptr;
-    while ((ident = consumeIdent<CSSValuePaint, CSSValueLayout, CSSValueStyle>(range))) {
-        if (list->hasValue(ident.get()))
+    while (true) {
+        CSSPrimitiveValue* ident = consumeIdent<CSSValuePaint, CSSValueLayout, CSSValueStyle>(range);
+        if (!ident)
+            break;
+        if (list->hasValue(ident))
             return nullptr;
-        list->append(ident.release());
+        list->append(ident);
     }
 
     if (!list->length())
         return nullptr;
-    return list.release();
+    return list;
 }
 
-static RawPtr<CSSValue> consumePath(CSSParserTokenRange& range)
+static CSSValue* consumePath(CSSParserTokenRange& range)
 {
     // FIXME: Add support for <url>, <basic-shape>, <geometry-box>.
     if (range.peek().functionId() != CSSValuePath)
@@ -1382,7 +1393,7 @@
     return CSSPathValue::create(byteStream.release());
 }
 
-static RawPtr<CSSValue> consumePathOrNone(CSSParserTokenRange& range)
+static CSSValue* consumePathOrNone(CSSParserTokenRange& range)
 {
     CSSValueID id = range.peek().id();
     if (id == CSSValueNone)
@@ -1391,51 +1402,51 @@
     return consumePath(range);
 }
 
-static RawPtr<CSSValue> consumeMotionRotation(CSSParserTokenRange& range)
+static CSSValue* consumeMotionRotation(CSSParserTokenRange& range)
 {
-    RawPtr<CSSValue> angle = consumeAngle(range);
-    RawPtr<CSSValue> keyword = consumeIdent<CSSValueAuto, CSSValueReverse>(range);
+    CSSValue* angle = consumeAngle(range);
+    CSSValue* keyword = consumeIdent<CSSValueAuto, CSSValueReverse>(range);
     if (!angle && !keyword)
         return nullptr;
 
     if (!angle)
         angle = consumeAngle(range);
 
-    RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    CSSValueList* list = CSSValueList::createSpaceSeparated();
     if (keyword)
-        list->append(keyword.release());
+        list->append(keyword);
     if (angle)
-        list->append(angle.release());
-    return list.release();
+        list->append(angle);
+    return list;
 }
 
-static RawPtr<CSSValue> consumeTextEmphasisStyle(CSSParserTokenRange& range)
+static CSSValue* consumeTextEmphasisStyle(CSSParserTokenRange& range)
 {
     CSSValueID id = range.peek().id();
     if (id == CSSValueNone)
         return consumeIdent(range);
 
-    if (RawPtr<CSSValue> textEmphasisStyle = consumeString(range))
-        return textEmphasisStyle.release();
+    if (CSSValue* textEmphasisStyle = consumeString(range))
+        return textEmphasisStyle;
 
-    RawPtr<CSSPrimitiveValue> fill = consumeIdent<CSSValueFilled, CSSValueOpen>(range);
-    RawPtr<CSSPrimitiveValue> shape = consumeIdent<CSSValueDot, CSSValueCircle, CSSValueDoubleCircle, CSSValueTriangle, CSSValueSesame>(range);
+    CSSPrimitiveValue* fill = consumeIdent<CSSValueFilled, CSSValueOpen>(range);
+    CSSPrimitiveValue* shape = consumeIdent<CSSValueDot, CSSValueCircle, CSSValueDoubleCircle, CSSValueTriangle, CSSValueSesame>(range);
     if (!fill)
         fill = consumeIdent<CSSValueFilled, CSSValueOpen>(range);
     if (fill && shape) {
-        RawPtr<CSSValueList> parsedValues = CSSValueList::createSpaceSeparated();
-        parsedValues->append(fill.release());
-        parsedValues->append(shape.release());
-        return parsedValues.release();
+        CSSValueList* parsedValues = CSSValueList::createSpaceSeparated();
+        parsedValues->append(fill);
+        parsedValues->append(shape);
+        return parsedValues;
     }
     if (fill)
-        return fill.release();
+        return fill;
     if (shape)
-        return shape.release();
+        return shape;
     return nullptr;
 }
 
-static RawPtr<CSSValue> consumeOutlineColor(CSSParserTokenRange& range, CSSParserMode cssParserMode)
+static CSSValue* consumeOutlineColor(CSSParserTokenRange& range, CSSParserMode cssParserMode)
 {
     // Outline color has "invert" as additional keyword.
     // Also, we want to allow the special focus color even in HTML Standard parsing mode.
@@ -1444,7 +1455,7 @@
     return consumeColor(range, cssParserMode);
 }
 
-static RawPtr<CSSPrimitiveValue> consumeLineWidth(CSSParserTokenRange& range, CSSParserMode cssParserMode, UnitlessQuirk unitless)
+static CSSPrimitiveValue* consumeLineWidth(CSSParserTokenRange& range, CSSParserMode cssParserMode, UnitlessQuirk unitless)
 {
     CSSValueID id = range.peek().id();
     if (id == CSSValueThin || id == CSSValueMedium || id == CSSValueThick)
@@ -1452,25 +1463,25 @@
     return consumeLength(range, cssParserMode, ValueRangeNonNegative, unitless);
 }
 
-static RawPtr<CSSPrimitiveValue> consumeBorderWidth(CSSParserTokenRange& range, CSSParserMode cssParserMode, UnitlessQuirk unitless)
+static CSSPrimitiveValue* consumeBorderWidth(CSSParserTokenRange& range, CSSParserMode cssParserMode, UnitlessQuirk unitless)
 {
     return consumeLineWidth(range, cssParserMode, unitless);
 }
 
-static RawPtr<CSSPrimitiveValue> consumeTextStrokeWidth(CSSParserTokenRange& range, CSSParserMode cssParserMode)
+static CSSPrimitiveValue* consumeTextStrokeWidth(CSSParserTokenRange& range, CSSParserMode cssParserMode)
 {
     return consumeLineWidth(range, cssParserMode, UnitlessQuirk::Forbid);
 }
 
-static RawPtr<CSSPrimitiveValue> consumeColumnRuleWidth(CSSParserTokenRange& range, CSSParserMode cssParserMode)
+static CSSPrimitiveValue* consumeColumnRuleWidth(CSSParserTokenRange& range, CSSParserMode cssParserMode)
 {
     return consumeLineWidth(range, cssParserMode, UnitlessQuirk::Forbid);
 }
 
-static bool consumeTranslate3d(CSSParserTokenRange& args, CSSParserMode cssParserMode, RawPtr<CSSFunctionValue>& transformValue)
+static bool consumeTranslate3d(CSSParserTokenRange& args, CSSParserMode cssParserMode, CSSFunctionValue*& transformValue)
 {
     unsigned numberOfArguments = 2;
-    RawPtr<CSSValue> parsedValue = nullptr;
+    CSSValue* parsedValue = nullptr;
     do {
         parsedValue = consumeLengthOrPercent(args, cssParserMode, ValueRangeAll);
         if (!parsedValue)
@@ -1486,10 +1497,10 @@
     return true;
 }
 
-static bool consumeNumbers(CSSParserTokenRange& args, RawPtr<CSSFunctionValue>& transformValue, unsigned numberOfArguments)
+static bool consumeNumbers(CSSParserTokenRange& args, CSSFunctionValue*& transformValue, unsigned numberOfArguments)
 {
     do {
-        RawPtr<CSSValue> parsedValue = consumeNumber(args, ValueRangeAll);
+        CSSValue* parsedValue = consumeNumber(args, ValueRangeAll);
         if (!parsedValue)
             return false;
         transformValue->append(parsedValue);
@@ -1499,9 +1510,9 @@
     return true;
 }
 
-static bool consumePerspective(CSSParserTokenRange& args, CSSParserMode cssParserMode, RawPtr<CSSFunctionValue>& transformValue, bool useLegacyParsing)
+static bool consumePerspective(CSSParserTokenRange& args, CSSParserMode cssParserMode, CSSFunctionValue*& transformValue, bool useLegacyParsing)
 {
-    RawPtr<CSSPrimitiveValue> parsedValue = consumeLength(args, cssParserMode, ValueRangeNonNegative);
+    CSSPrimitiveValue* parsedValue = consumeLength(args, cssParserMode, ValueRangeNonNegative);
     if (!parsedValue && useLegacyParsing) {
         double perspective;
         if (!consumeNumberRaw(args, perspective) || perspective < 0)
@@ -1514,7 +1525,7 @@
     return true;
 }
 
-static RawPtr<CSSValue> consumeTransformValue(CSSParserTokenRange& range, CSSParserMode cssParserMode, bool useLegacyParsing)
+static CSSValue* consumeTransformValue(CSSParserTokenRange& range, CSSParserMode cssParserMode, bool useLegacyParsing)
 {
     CSSValueID functionId = range.peek().functionId();
     if (functionId == CSSValueInvalid)
@@ -1522,8 +1533,8 @@
     CSSParserTokenRange args = consumeFunction(range);
     if (args.atEnd())
         return nullptr;
-    RawPtr<CSSFunctionValue> transformValue = CSSFunctionValue::create(functionId);
-    RawPtr<CSSValue> parsedValue = nullptr;
+    CSSFunctionValue* transformValue = CSSFunctionValue::create(functionId);
+    CSSValue* parsedValue = nullptr;
     switch (functionId) {
     case CSSValueRotate:
     case CSSValueRotateX:
@@ -1603,27 +1614,27 @@
         transformValue->append(parsedValue);
     if (!args.atEnd())
         return nullptr;
-    return transformValue.release();
+    return transformValue;
 }
 
-static RawPtr<CSSValue> consumeTransform(CSSParserTokenRange& range, CSSParserMode cssParserMode, bool useLegacyParsing)
+static CSSValue* consumeTransform(CSSParserTokenRange& range, CSSParserMode cssParserMode, bool useLegacyParsing)
 {
     if (range.peek().id() == CSSValueNone)
         return consumeIdent(range);
 
-    RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    CSSValueList* list = CSSValueList::createSpaceSeparated();
     do {
-        RawPtr<CSSValue> parsedTransformValue = consumeTransformValue(range, cssParserMode, useLegacyParsing);
+        CSSValue* parsedTransformValue = consumeTransformValue(range, cssParserMode, useLegacyParsing);
         if (!parsedTransformValue)
             return nullptr;
-        list->append(parsedTransformValue.release());
+        list->append(parsedTransformValue);
     } while (!range.atEnd());
 
-    return list.release();
+    return list;
 }
 
 template <CSSValueID start, CSSValueID end>
-static RawPtr<CSSValue> consumePositionLonghand(CSSParserTokenRange& range, CSSParserMode cssParserMode)
+static CSSValue* consumePositionLonghand(CSSParserTokenRange& range, CSSParserMode cssParserMode)
 {
     if (range.peek().type() == IdentToken) {
         CSSValueID id = range.peek().id();
@@ -1642,47 +1653,47 @@
     return consumeLengthOrPercent(range, cssParserMode, ValueRangeAll);
 }
 
-static RawPtr<CSSValue> consumePositionX(CSSParserTokenRange& range, CSSParserMode cssParserMode)
+static CSSValue* consumePositionX(CSSParserTokenRange& range, CSSParserMode cssParserMode)
 {
     return consumePositionLonghand<CSSValueLeft, CSSValueRight>(range, cssParserMode);
 }
 
-static RawPtr<CSSValue> consumePositionY(CSSParserTokenRange& range, CSSParserMode cssParserMode)
+static CSSValue* consumePositionY(CSSParserTokenRange& range, CSSParserMode cssParserMode)
 {
     return consumePositionLonghand<CSSValueTop, CSSValueBottom>(range, cssParserMode);
 }
 
-static RawPtr<CSSValue> consumePaintStroke(CSSParserTokenRange& range, CSSParserMode cssParserMode)
+static CSSValue* consumePaintStroke(CSSParserTokenRange& range, CSSParserMode cssParserMode)
 {
     if (range.peek().id() == CSSValueNone)
         return consumeIdent(range);
     String url = consumeUrl(range);
     if (!url.isNull()) {
-        RawPtr<CSSValue> parsedValue = nullptr;
+        CSSValue* parsedValue = nullptr;
         if (range.peek().id() == CSSValueNone)
             parsedValue = consumeIdent(range);
         else
             parsedValue = consumeColor(range, cssParserMode);
         if (parsedValue) {
-            RawPtr<CSSValueList> values = CSSValueList::createSpaceSeparated();
+            CSSValueList* values = CSSValueList::createSpaceSeparated();
             values->append(CSSURIValue::create(url));
             values->append(parsedValue);
-            return values.release();
+            return values;
         }
         return CSSURIValue::create(url);
     }
     return consumeColor(range, cssParserMode);
 }
 
-static RawPtr<CSSValue> consumePaintOrder(CSSParserTokenRange& range)
+static CSSValue* consumePaintOrder(CSSParserTokenRange& range)
 {
     if (range.peek().id() == CSSValueNormal)
         return consumeIdent(range);
 
     Vector<CSSValueID, 3> paintTypeList;
-    RawPtr<CSSPrimitiveValue> fill = nullptr;
-    RawPtr<CSSPrimitiveValue> stroke = nullptr;
-    RawPtr<CSSPrimitiveValue> markers = nullptr;
+    CSSPrimitiveValue* fill = nullptr;
+    CSSPrimitiveValue* stroke = nullptr;
+    CSSPrimitiveValue* markers = nullptr;
     do {
         CSSValueID id = range.peek().id();
         if (id == CSSValueFill && !fill)
@@ -1700,31 +1711,31 @@
     // pop a last list items from CSSValueList without bigger cost, we create the
     // list after parsing.
     CSSValueID firstPaintOrderType = paintTypeList.at(0);
-    RawPtr<CSSValueList> paintOrderList = CSSValueList::createSpaceSeparated();
+    CSSValueList* paintOrderList = CSSValueList::createSpaceSeparated();
     switch (firstPaintOrderType) {
     case CSSValueFill:
     case CSSValueStroke:
-        paintOrderList->append(firstPaintOrderType == CSSValueFill ? fill.release() : stroke.release());
+        paintOrderList->append(firstPaintOrderType == CSSValueFill ? fill : stroke);
         if (paintTypeList.size() > 1) {
             if (paintTypeList.at(1) == CSSValueMarkers)
-                paintOrderList->append(markers.release());
+                paintOrderList->append(markers);
         }
         break;
     case CSSValueMarkers:
-        paintOrderList->append(markers.release());
+        paintOrderList->append(markers);
         if (paintTypeList.size() > 1) {
             if (paintTypeList.at(1) == CSSValueStroke)
-                paintOrderList->append(stroke.release());
+                paintOrderList->append(stroke);
         }
         break;
     default:
         ASSERT_NOT_REACHED();
     }
 
-    return paintOrderList.release();
+    return paintOrderList;
 }
 
-static RawPtr<CSSValue> consumeNoneOrURI(CSSParserTokenRange& range)
+static CSSValue* consumeNoneOrURI(CSSParserTokenRange& range)
 {
     if (range.peek().id() == CSSValueNone)
         return consumeIdent(range);
@@ -1735,7 +1746,7 @@
     return CSSURIValue::create(url);
 }
 
-static RawPtr<CSSValue> consumeFlexBasis(CSSParserTokenRange& range, CSSParserMode cssParserMode)
+static CSSValue* consumeFlexBasis(CSSParserTokenRange& range, CSSParserMode cssParserMode)
 {
     // FIXME: Support intrinsic dimensions too.
     if (range.peek().id() == CSSValueAuto)
@@ -1743,23 +1754,23 @@
     return consumeLengthOrPercent(range, cssParserMode, ValueRangeNonNegative);
 }
 
-static RawPtr<CSSValue> consumeStrokeDasharray(CSSParserTokenRange& range)
+static CSSValue* consumeStrokeDasharray(CSSParserTokenRange& range)
 {
     CSSValueID id = range.peek().id();
     if (id == CSSValueNone)
         return consumeIdent(range);
 
-    RawPtr<CSSValueList> dashes = CSSValueList::createCommaSeparated();
+    CSSValueList* dashes = CSSValueList::createCommaSeparated();
     do {
-        RawPtr<CSSPrimitiveValue> dash = consumeLengthOrPercent(range, SVGAttributeMode, ValueRangeNonNegative, UnitlessQuirk::Allow);
+        CSSPrimitiveValue* dash = consumeLengthOrPercent(range, SVGAttributeMode, ValueRangeNonNegative, UnitlessQuirk::Allow);
         if (!dash || (consumeCommaIncludingWhitespace(range) && range.atEnd()))
             return nullptr;
-        dashes->append(dash.release());
+        dashes->append(dash);
     } while (!range.atEnd());
-    return dashes.release();
+    return dashes;
 }
 
-static RawPtr<CSSPrimitiveValue> consumeBaselineShift(CSSParserTokenRange& range)
+static CSSPrimitiveValue* consumeBaselineShift(CSSParserTokenRange& range)
 {
     CSSValueID id = range.peek().id();
     if (id == CSSValueBaseline || id == CSSValueSub || id == CSSValueSuper)
@@ -1767,24 +1778,24 @@
     return consumeLengthOrPercent(range, SVGAttributeMode, ValueRangeAll);
 }
 
-static RawPtr<CSSValue> createCSSImageValueWithReferrer(const AtomicString& rawValue, const CSSParserContext& context)
+static CSSValue* createCSSImageValueWithReferrer(const AtomicString& rawValue, const CSSParserContext& context)
 {
-    RawPtr<CSSValue> imageValue = CSSImageValue::create(rawValue, context.completeURL(rawValue));
-    toCSSImageValue(imageValue.get())->setReferrer(context.referrer());
+    CSSValue* imageValue = CSSImageValue::create(rawValue, context.completeURL(rawValue));
+    toCSSImageValue(imageValue)->setReferrer(context.referrer());
     return imageValue;
 }
 
-static RawPtr<CSSValue> consumeImageSet(CSSParserTokenRange& range, const CSSParserContext& context)
+static CSSValue* consumeImageSet(CSSParserTokenRange& range, const CSSParserContext& context)
 {
     CSSParserTokenRange rangeCopy = range;
     CSSParserTokenRange args = consumeFunction(rangeCopy);
-    RawPtr<CSSImageSetValue> imageSet = CSSImageSetValue::create();
+    CSSImageSetValue* imageSet = CSSImageSetValue::create();
     do {
         AtomicString urlValue(consumeUrl(args));
         if (urlValue.isNull())
             return nullptr;
 
-        RawPtr<CSSValue> image = createCSSImageValueWithReferrer(urlValue, context);
+        CSSValue* image = createCSSImageValueWithReferrer(urlValue, context);
         imageSet->append(image);
 
         const CSSParserToken& token = args.consumeIncludingWhitespace();
@@ -1801,14 +1812,14 @@
     if (!args.atEnd())
         return nullptr;
     range = rangeCopy;
-    return imageSet.release();
+    return imageSet;
 }
 
-static RawPtr<CSSValue> consumeCursor(CSSParserTokenRange& range, const CSSParserContext& context, bool inQuirksMode)
+static CSSValue* consumeCursor(CSSParserTokenRange& range, const CSSParserContext& context, bool inQuirksMode)
 {
-    RawPtr<CSSValueList> list = nullptr;
+    CSSValueList* list = nullptr;
     while (true) {
-        RawPtr<CSSValue> image = nullptr;
+        CSSValue* image = nullptr;
         AtomicString uri(consumeUrl(range));
         if (!uri.isNull()) {
             image = createCSSImageValueWithReferrer(uri, context);
@@ -1846,7 +1857,7 @@
         else if (id == CSSValueWebkitZoomOut)
             context.useCounter()->count(UseCounter::PrefixedCursorZoomOut);
     }
-    RawPtr<CSSValue> cursorType = nullptr;
+    CSSValue* cursorType = nullptr;
     if (id == CSSValueHand) {
         if (!inQuirksMode) // Non-standard behavior
             return nullptr;
@@ -1859,13 +1870,13 @@
     }
 
     if (!list)
-        return cursorType.release();
-    list->append(cursorType.release());
-    return list.release();
+        return cursorType;
+    list->append(cursorType);
+    return list;
 }
 
 // This should go away once we drop support for -webkit-gradient
-static RawPtr<CSSPrimitiveValue> consumeDeprecatedGradientPoint(CSSParserTokenRange& args, bool horizontal)
+static CSSPrimitiveValue* consumeDeprecatedGradientPoint(CSSParserTokenRange& args, bool horizontal)
 {
     if (args.peek().type() == IdentToken) {
         if ((horizontal && consumeIdent<CSSValueLeft>(args)) || (!horizontal && consumeIdent<CSSValueTop>(args)))
@@ -1876,14 +1887,14 @@
             return cssValuePool().createValue(50., CSSPrimitiveValue::UnitType::Percentage);
         return nullptr;
     }
-    RawPtr<CSSPrimitiveValue> result = consumePercent(args, ValueRangeAll);
+    CSSPrimitiveValue* result = consumePercent(args, ValueRangeAll);
     if (!result)
         result = consumeNumber(args, ValueRangeAll);
     return result;
 }
 
 // Used to parse colors for -webkit-gradient(...).
-static RawPtr<CSSValue> consumeDeprecatedGradientStopColor(CSSParserTokenRange& args, CSSParserMode cssParserMode)
+static CSSValue* consumeDeprecatedGradientStopColor(CSSParserTokenRange& args, CSSParserMode cssParserMode)
 {
     if (args.peek().id() == CSSValueCurrentcolor)
         return nullptr;
@@ -1919,9 +1930,9 @@
     return stop.m_color && args.atEnd();
 }
 
-static RawPtr<CSSValue> consumeDeprecatedGradient(CSSParserTokenRange& args, CSSParserMode cssParserMode)
+static CSSValue* consumeDeprecatedGradient(CSSParserTokenRange& args, CSSParserMode cssParserMode)
 {
-    RawPtr<CSSGradientValue> result = nullptr;
+    CSSGradientValue* result = nullptr;
     CSSValueID id = args.consumeIncludingWhitespace().id();
     bool isDeprecatedRadialGradient = (id == CSSValueRadial);
     if (isDeprecatedRadialGradient)
@@ -1931,43 +1942,43 @@
     if (!result || !consumeCommaIncludingWhitespace(args))
         return nullptr;
 
-    RawPtr<CSSPrimitiveValue> point = consumeDeprecatedGradientPoint(args, true);
+    CSSPrimitiveValue* point = consumeDeprecatedGradientPoint(args, true);
     if (!point)
         return nullptr;
-    result->setFirstX(point.release());
+    result->setFirstX(point);
     point = consumeDeprecatedGradientPoint(args, false);
     if (!point)
         return nullptr;
-    result->setFirstY(point.release());
+    result->setFirstY(point);
 
     if (!consumeCommaIncludingWhitespace(args))
         return nullptr;
 
     // For radial gradients only, we now expect a numeric radius.
     if (isDeprecatedRadialGradient) {
-        RawPtr<CSSPrimitiveValue> radius = consumeNumber(args, ValueRangeAll);
+        CSSPrimitiveValue* radius = consumeNumber(args, ValueRangeAll);
         if (!radius || !consumeCommaIncludingWhitespace(args))
             return nullptr;
-        toCSSRadialGradientValue(result.get())->setFirstRadius(radius.release());
+        toCSSRadialGradientValue(result)->setFirstRadius(radius);
     }
 
     point = consumeDeprecatedGradientPoint(args, true);
     if (!point)
         return nullptr;
-    result->setSecondX(point.release());
+    result->setSecondX(point);
     point = consumeDeprecatedGradientPoint(args, false);
     if (!point)
         return nullptr;
-    result->setSecondY(point.release());
+    result->setSecondY(point);
 
     // For radial gradients only, we now expect the second radius.
     if (isDeprecatedRadialGradient) {
         if (!consumeCommaIncludingWhitespace(args))
             return nullptr;
-        RawPtr<CSSPrimitiveValue> radius = consumeNumber(args, ValueRangeAll);
+        CSSPrimitiveValue* radius = consumeNumber(args, ValueRangeAll);
         if (!radius)
             return nullptr;
-        toCSSRadialGradientValue(result.get())->setSecondRadius(radius.release());
+        toCSSRadialGradientValue(result)->setSecondRadius(radius);
     }
 
     CSSGradientColorStop stop;
@@ -1977,7 +1988,7 @@
         result->addStop(stop);
     }
 
-    return result.release();
+    return result;
 }
 
 static bool consumeGradientColorStops(CSSParserTokenRange& range, CSSParserMode cssParserMode, CSSGradientValue* gradient)
@@ -2007,22 +2018,22 @@
     return gradient->stopCount() >= 2;
 }
 
-static RawPtr<CSSValue> consumeDeprecatedRadialGradient(CSSParserTokenRange& args, CSSParserMode cssParserMode, CSSGradientRepeat repeating)
+static CSSValue* consumeDeprecatedRadialGradient(CSSParserTokenRange& args, CSSParserMode cssParserMode, CSSGradientRepeat repeating)
 {
-    RawPtr<CSSRadialGradientValue> result = CSSRadialGradientValue::create(repeating, CSSPrefixedRadialGradient);
-    RawPtr<CSSValue> centerX = nullptr;
-    RawPtr<CSSValue> centerY = nullptr;
+    CSSRadialGradientValue* result = CSSRadialGradientValue::create(repeating, CSSPrefixedRadialGradient);
+    CSSValue* centerX = nullptr;
+    CSSValue* centerY = nullptr;
     consumeOneOrTwoValuedPosition(args, cssParserMode, UnitlessQuirk::Forbid, centerX, centerY);
     if ((centerX || centerY) && !consumeCommaIncludingWhitespace(args))
         return nullptr;
 
-    result->setFirstX(toCSSPrimitiveValue(centerX.get()));
-    result->setSecondX(toCSSPrimitiveValue(centerX.get()));
-    result->setFirstY(toCSSPrimitiveValue(centerY.get()));
-    result->setSecondY(toCSSPrimitiveValue(centerY.get()));
+    result->setFirstX(toCSSPrimitiveValue(centerX));
+    result->setSecondX(toCSSPrimitiveValue(centerX));
+    result->setFirstY(toCSSPrimitiveValue(centerY));
+    result->setSecondY(toCSSPrimitiveValue(centerY));
 
-    RawPtr<CSSPrimitiveValue> shape = consumeIdent<CSSValueCircle, CSSValueEllipse>(args);
-    RawPtr<CSSPrimitiveValue> sizeKeyword = consumeIdent<CSSValueClosestSide, CSSValueClosestCorner, CSSValueFarthestSide, CSSValueFarthestCorner, CSSValueContain, CSSValueCover>(args);
+    CSSPrimitiveValue* shape = consumeIdent<CSSValueCircle, CSSValueEllipse>(args);
+    CSSPrimitiveValue* sizeKeyword = consumeIdent<CSSValueClosestSide, CSSValueClosestCorner, CSSValueFarthestSide, CSSValueFarthestCorner, CSSValueContain, CSSValueCover>(args);
     if (!shape)
         shape = consumeIdent<CSSValueCircle, CSSValueEllipse>(args);
     result->setShape(shape);
@@ -2030,9 +2041,9 @@
 
     // Or, two lengths or percentages
     if (!shape && !sizeKeyword) {
-        RawPtr<CSSPrimitiveValue> horizontalSize = nullptr;
-        RawPtr<CSSPrimitiveValue> verticalSize = nullptr;
-        if ((horizontalSize = consumeLengthOrPercent(args, cssParserMode, ValueRangeAll))) {
+        CSSPrimitiveValue* horizontalSize = consumeLengthOrPercent(args, cssParserMode, ValueRangeAll);
+        CSSPrimitiveValue* verticalSize = nullptr;
+        if (horizontalSize) {
             verticalSize = consumeLengthOrPercent(args, cssParserMode, ValueRangeAll);
             if (!verticalSize)
                 return nullptr;
@@ -2043,20 +2054,20 @@
     } else {
         consumeCommaIncludingWhitespace(args);
     }
-    if (!consumeGradientColorStops(args, cssParserMode, result.get()))
+    if (!consumeGradientColorStops(args, cssParserMode, result))
         return nullptr;
 
-    return result.release();
+    return result;
 }
 
-static RawPtr<CSSValue> consumeRadialGradient(CSSParserTokenRange& args, CSSParserMode cssParserMode, CSSGradientRepeat repeating)
+static CSSValue* consumeRadialGradient(CSSParserTokenRange& args, CSSParserMode cssParserMode, CSSGradientRepeat repeating)
 {
-    RawPtr<CSSRadialGradientValue> result = CSSRadialGradientValue::create(repeating, CSSRadialGradient);
+    CSSRadialGradientValue* result = CSSRadialGradientValue::create(repeating, CSSRadialGradient);
 
-    RawPtr<CSSPrimitiveValue> shape = nullptr;
-    RawPtr<CSSPrimitiveValue> sizeKeyword = nullptr;
-    RawPtr<CSSPrimitiveValue> horizontalSize = nullptr;
-    RawPtr<CSSPrimitiveValue> verticalSize = nullptr;
+    CSSPrimitiveValue* shape = nullptr;
+    CSSPrimitiveValue* sizeKeyword = nullptr;
+    CSSPrimitiveValue* horizontalSize = nullptr;
+    CSSPrimitiveValue* verticalSize = nullptr;
 
     // First part of grammar, the size/shape clause:
     // [ circle || <length> ] |
@@ -2077,14 +2088,15 @@
                 break;
             }
         } else {
-            RawPtr<CSSPrimitiveValue> center = consumeLengthOrPercent(args, cssParserMode, ValueRangeAll);
+            CSSPrimitiveValue* center = consumeLengthOrPercent(args, cssParserMode, ValueRangeAll);
             if (!center)
                 break;
             if (horizontalSize)
                 return nullptr;
             horizontalSize = center;
-            if ((center = consumeLengthOrPercent(args, cssParserMode, ValueRangeAll))) {
-                verticalSize = center.release();
+            center = consumeLengthOrPercent(args, cssParserMode, ValueRangeAll);
+            if (center) {
+                verticalSize = center;
                 ++i;
             }
         }
@@ -2109,8 +2121,8 @@
     result->setEndHorizontalSize(horizontalSize);
     result->setEndVerticalSize(verticalSize);
 
-    RawPtr<CSSValue> centerX = nullptr;
-    RawPtr<CSSValue> centerY = nullptr;
+    CSSValue* centerX = nullptr;
+    CSSValue* centerY = nullptr;
     if (args.peek().id() == CSSValueAt) {
         args.consumeIncludingWhitespace();
         consumePosition(args, cssParserMode, UnitlessQuirk::Forbid, centerX, centerY);
@@ -2125,22 +2137,22 @@
 
     if ((shape || sizeKeyword || horizontalSize || centerX || centerY) && !consumeCommaIncludingWhitespace(args))
         return nullptr;
-    if (!consumeGradientColorStops(args, cssParserMode, result.get()))
+    if (!consumeGradientColorStops(args, cssParserMode, result))
         return nullptr;
-    return result.release();
+    return result;
 }
 
-static RawPtr<CSSValue> consumeLinearGradient(CSSParserTokenRange& args, CSSParserMode cssParserMode, CSSGradientRepeat repeating, CSSGradientType gradientType)
+static CSSValue* consumeLinearGradient(CSSParserTokenRange& args, CSSParserMode cssParserMode, CSSGradientRepeat repeating, CSSGradientType gradientType)
 {
-    RawPtr<CSSLinearGradientValue> result = CSSLinearGradientValue::create(repeating, gradientType);
+    CSSLinearGradientValue* result = CSSLinearGradientValue::create(repeating, gradientType);
 
     bool expectComma = true;
-    RawPtr<CSSPrimitiveValue> angle = consumeAngle(args);
+    CSSPrimitiveValue* angle = consumeAngle(args);
     if (angle) {
-        result->setAngle(angle.release());
+        result->setAngle(angle);
     } else if (gradientType == CSSPrefixedLinearGradient || consumeIdent<CSSValueTo>(args)) {
-        RawPtr<CSSPrimitiveValue> endX = consumeIdent<CSSValueLeft, CSSValueRight>(args);
-        RawPtr<CSSPrimitiveValue> endY = consumeIdent<CSSValueBottom, CSSValueTop>(args);
+        CSSPrimitiveValue* endX = consumeIdent<CSSValueLeft, CSSValueRight>(args);
+        CSSPrimitiveValue* endY = consumeIdent<CSSValueBottom, CSSValueTop>(args);
         if (!endX && !endY) {
             if (gradientType == CSSLinearGradient)
                 return nullptr;
@@ -2150,31 +2162,31 @@
             endX = consumeIdent<CSSValueLeft, CSSValueRight>(args);
         }
 
-        result->setFirstX(endX.release());
-        result->setFirstY(endY.release());
+        result->setFirstX(endX);
+        result->setFirstY(endY);
     } else {
         expectComma = false;
     }
 
     if (expectComma && !consumeCommaIncludingWhitespace(args))
         return nullptr;
-    if (!consumeGradientColorStops(args, cssParserMode, result.get()))
+    if (!consumeGradientColorStops(args, cssParserMode, result))
         return nullptr;
-    return result.release();
+    return result;
 }
 
-static RawPtr<CSSValue> consumeImageOrNone(CSSParserTokenRange&, CSSParserContext);
+static CSSValue* consumeImageOrNone(CSSParserTokenRange&, CSSParserContext);
 
-static RawPtr<CSSValue> consumeCrossFade(CSSParserTokenRange& args, CSSParserContext context)
+static CSSValue* consumeCrossFade(CSSParserTokenRange& args, CSSParserContext context)
 {
-    RawPtr<CSSValue> fromImageValue = consumeImageOrNone(args, context);
+    CSSValue* fromImageValue = consumeImageOrNone(args, context);
     if (!fromImageValue || !consumeCommaIncludingWhitespace(args))
         return nullptr;
-    RawPtr<CSSValue> toImageValue = consumeImageOrNone(args, context);
+    CSSValue* toImageValue = consumeImageOrNone(args, context);
     if (!toImageValue || !consumeCommaIncludingWhitespace(args))
         return nullptr;
 
-    RawPtr<CSSPrimitiveValue> percentage = nullptr;
+    CSSPrimitiveValue* percentage = nullptr;
     const CSSParserToken& percentageArg = args.consumeIncludingWhitespace();
     if (percentageArg.type() == PercentageToken)
         percentage = cssValuePool().createValue(clampTo<double>(percentageArg.numericValue() / 100, 0, 1), CSSPrimitiveValue::UnitType::Number);
@@ -2186,23 +2198,23 @@
     return CSSCrossfadeValue::create(fromImageValue, toImageValue, percentage);
 }
 
-static RawPtr<CSSValue> consumePaint(CSSParserTokenRange& args, CSSParserContext context)
+static CSSValue* consumePaint(CSSParserTokenRange& args, CSSParserContext context)
 {
     ASSERT(RuntimeEnabledFeatures::cssPaintAPIEnabled());
 
-    RawPtr<CSSCustomIdentValue> name = consumeCustomIdent(args);
+    CSSCustomIdentValue* name = consumeCustomIdent(args);
     if (!name)
         return nullptr;
 
-    return CSSPaintValue::create(name.release());
+    return CSSPaintValue::create(name);
 }
 
-static RawPtr<CSSValue> consumeGeneratedImage(CSSParserTokenRange& range, CSSParserContext context)
+static CSSValue* consumeGeneratedImage(CSSParserTokenRange& range, CSSParserContext context)
 {
     CSSValueID id = range.peek().functionId();
     CSSParserTokenRange rangeCopy = range;
     CSSParserTokenRange args = consumeFunction(rangeCopy);
-    RawPtr<CSSValue> result = nullptr;
+    CSSValue* result = nullptr;
     if (id == CSSValueRadialGradient) {
         result = consumeRadialGradient(args, context.mode(), NonRepeating);
     } else if (id == CSSValueRepeatingRadialGradient) {
@@ -2255,7 +2267,7 @@
         || id == CSSValueWebkitGradient || id == CSSValueWebkitCrossFade || id == CSSValuePaint;
 }
 
-static RawPtr<CSSValue> consumeImage(CSSParserTokenRange& range, CSSParserContext context)
+static CSSValue* consumeImage(CSSParserTokenRange& range, CSSParserContext context)
 {
     AtomicString uri(consumeUrl(range));
     if (!uri.isNull())
@@ -2270,14 +2282,14 @@
     return nullptr;
 }
 
-static RawPtr<CSSValue> consumeImageOrNone(CSSParserTokenRange& range, CSSParserContext context)
+static CSSValue* consumeImageOrNone(CSSParserTokenRange& range, CSSParserContext context)
 {
     if (range.peek().id() == CSSValueNone)
         return consumeIdent(range);
     return consumeImage(range, context);
 }
 
-static RawPtr<CSSValue> consumeAttr(CSSParserTokenRange args, CSSParserContext context)
+static CSSValue* consumeAttr(CSSParserTokenRange args, CSSParserContext context)
 {
     if (args.peek().type() != IdentToken)
         return nullptr;
@@ -2293,19 +2305,19 @@
     if (context.isHTMLDocument())
         attrName = attrName.lower();
 
-    RawPtr<CSSFunctionValue> attrValue = CSSFunctionValue::create(CSSValueAttr);
+    CSSFunctionValue* attrValue = CSSFunctionValue::create(CSSValueAttr);
     attrValue->append(CSSCustomIdentValue::create(attrName));
-    return attrValue.release();
+    return attrValue;
 }
 
-static RawPtr<CSSValue> consumeCounterContent(CSSParserTokenRange args, bool counters)
+static CSSValue* consumeCounterContent(CSSParserTokenRange args, bool counters)
 {
-    RawPtr<CSSCustomIdentValue> identifier = consumeCustomIdent(args);
+    CSSCustomIdentValue* identifier = consumeCustomIdent(args);
     if (!identifier)
         return nullptr;
 
     // TODO(timloh): Make this a CSSStringValue.
-    RawPtr<CSSCustomIdentValue> separator = nullptr;
+    CSSCustomIdentValue* separator = nullptr;
     if (!counters) {
         separator = CSSCustomIdentValue::create(String());
     } else {
@@ -2316,7 +2328,7 @@
         separator = CSSCustomIdentValue::create(args.consumeIncludingWhitespace().value());
     }
 
-    RawPtr<CSSPrimitiveValue> listStyle = nullptr;
+    CSSPrimitiveValue* listStyle = nullptr;
     if (consumeCommaIncludingWhitespace(args)) {
         CSSValueID id = args.peek().id();
         if ((id != CSSValueNone && (id < CSSValueDisc || id > CSSValueKatakanaIroha)))
@@ -2328,18 +2340,18 @@
 
     if (!args.atEnd())
         return nullptr;
-    return CSSCounterValue::create(identifier.release(), listStyle.release(), separator.release());
+    return CSSCounterValue::create(identifier, listStyle, separator);
 }
 
-static RawPtr<CSSValue> consumeContent(CSSParserTokenRange& range, CSSParserContext context)
+static CSSValue* consumeContent(CSSParserTokenRange& range, CSSParserContext context)
 {
     if (identMatches<CSSValueNone, CSSValueNormal>(range.peek().id()))
         return consumeIdent(range);
 
-    RawPtr<CSSValueList> values = CSSValueList::createSpaceSeparated();
+    CSSValueList* values = CSSValueList::createSpaceSeparated();
 
     do {
-        RawPtr<CSSValue> parsedValue = consumeImage(range, context);
+        CSSValue* parsedValue = consumeImage(range, context);
         if (!parsedValue)
             parsedValue = consumeIdent<CSSValueOpenQuote, CSSValueCloseQuote, CSSValueNoOpenQuote, CSSValueNoCloseQuote>(range);
         if (!parsedValue)
@@ -2354,17 +2366,17 @@
             if (!parsedValue)
                 return nullptr;
         }
-        values->append(parsedValue.release());
+        values->append(parsedValue);
     } while (!range.atEnd());
 
-    return values.release();
+    return values;
 }
 
-static RawPtr<CSSPrimitiveValue> consumePerspective(CSSParserTokenRange& range, CSSParserMode cssParserMode, CSSPropertyID unresolvedProperty)
+static CSSPrimitiveValue* consumePerspective(CSSParserTokenRange& range, CSSParserMode cssParserMode, CSSPropertyID unresolvedProperty)
 {
     if (range.peek().id() == CSSValueNone)
         return consumeIdent(range);
-    RawPtr<CSSPrimitiveValue> parsedValue = consumeLength(range, cssParserMode, ValueRangeAll);
+    CSSPrimitiveValue* parsedValue = consumeLength(range, cssParserMode, ValueRangeAll);
     if (!parsedValue && (unresolvedProperty == CSSPropertyAliasWebkitPerspective)) {
         double perspective;
         if (!consumeNumberRaw(range, perspective))
@@ -2372,113 +2384,113 @@
         parsedValue = cssValuePool().createValue(perspective, CSSPrimitiveValue::UnitType::Pixels);
     }
     if (parsedValue && (parsedValue->isCalculated() || parsedValue->getDoubleValue() > 0))
-        return parsedValue.release();
+        return parsedValue;
     return nullptr;
 }
 
-static RawPtr<CSSValueList> consumePositionList(CSSParserTokenRange& range, CSSParserMode cssParserMode)
+static CSSValueList* consumePositionList(CSSParserTokenRange& range, CSSParserMode cssParserMode)
 {
-    RawPtr<CSSValueList> positions = CSSValueList::createCommaSeparated();
+    CSSValueList* positions = CSSValueList::createCommaSeparated();
     do {
-        RawPtr<CSSValue> position = consumePosition(range, cssParserMode, UnitlessQuirk::Forbid);
+        CSSValue* position = consumePosition(range, cssParserMode, UnitlessQuirk::Forbid);
         if (!position)
             return nullptr;
         positions->append(position);
     } while (consumeCommaIncludingWhitespace(range));
-    return positions.release();
+    return positions;
 }
 
-static RawPtr<CSSValue> consumeScrollSnapCoordinate(CSSParserTokenRange& range, CSSParserMode cssParserMode)
+static CSSValue* consumeScrollSnapCoordinate(CSSParserTokenRange& range, CSSParserMode cssParserMode)
 {
     if (range.peek().id() == CSSValueNone)
         return consumeIdent(range);
     return consumePositionList(range, cssParserMode);
 }
 
-static RawPtr<CSSValue> consumeScrollSnapPoints(CSSParserTokenRange& range, CSSParserMode cssParserMode)
+static CSSValue* consumeScrollSnapPoints(CSSParserTokenRange& range, CSSParserMode cssParserMode)
 {
     if (range.peek().id() == CSSValueNone)
         return consumeIdent(range);
     if (range.peek().functionId() == CSSValueRepeat) {
         CSSParserTokenRange args = consumeFunction(range);
-        RawPtr<CSSPrimitiveValue> parsedValue = consumeLengthOrPercent(args, cssParserMode, ValueRangeNonNegative);
+        CSSPrimitiveValue* parsedValue = consumeLengthOrPercent(args, cssParserMode, ValueRangeNonNegative);
         if (args.atEnd() && parsedValue && (parsedValue->isCalculated() || parsedValue->getDoubleValue() > 0)) {
-            RawPtr<CSSFunctionValue> result = CSSFunctionValue::create(CSSValueRepeat);
-            result->append(parsedValue.release());
-            return result.release();
+            CSSFunctionValue* result = CSSFunctionValue::create(CSSValueRepeat);
+            result->append(parsedValue);
+            return result;
         }
     }
     return nullptr;
 }
 
-static RawPtr<CSSValue> consumeBorderRadiusCorner(CSSParserTokenRange& range, CSSParserMode cssParserMode)
+static CSSValue* consumeBorderRadiusCorner(CSSParserTokenRange& range, CSSParserMode cssParserMode)
 {
-    RawPtr<CSSValue> parsedValue1 = consumeLengthOrPercent(range, cssParserMode, ValueRangeNonNegative);
+    CSSValue* parsedValue1 = consumeLengthOrPercent(range, cssParserMode, ValueRangeNonNegative);
     if (!parsedValue1)
         return nullptr;
-    RawPtr<CSSValue> parsedValue2 = consumeLengthOrPercent(range, cssParserMode, ValueRangeNonNegative);
+    CSSValue* parsedValue2 = consumeLengthOrPercent(range, cssParserMode, ValueRangeNonNegative);
     if (!parsedValue2)
         parsedValue2 = parsedValue1;
-    return CSSValuePair::create(parsedValue1.release(), parsedValue2.release(), CSSValuePair::DropIdenticalValues);
+    return CSSValuePair::create(parsedValue1, parsedValue2, CSSValuePair::DropIdenticalValues);
 }
 
-static RawPtr<CSSPrimitiveValue> consumeVerticalAlign(CSSParserTokenRange& range, CSSParserMode cssParserMode)
+static CSSPrimitiveValue* consumeVerticalAlign(CSSParserTokenRange& range, CSSParserMode cssParserMode)
 {
-    RawPtr<CSSPrimitiveValue> parsedValue = consumeIdentRange(range, CSSValueBaseline, CSSValueWebkitBaselineMiddle);
+    CSSPrimitiveValue* parsedValue = consumeIdentRange(range, CSSValueBaseline, CSSValueWebkitBaselineMiddle);
     if (!parsedValue)
         parsedValue = consumeLengthOrPercent(range, cssParserMode, ValueRangeAll, UnitlessQuirk::Allow);
-    return parsedValue.release();
+    return parsedValue;
 }
 
-static RawPtr<CSSPrimitiveValue> consumeShapeRadius(CSSParserTokenRange& args, CSSParserMode cssParserMode)
+static CSSPrimitiveValue* consumeShapeRadius(CSSParserTokenRange& args, CSSParserMode cssParserMode)
 {
     if (identMatches<CSSValueClosestSide, CSSValueFarthestSide>(args.peek().id()))
         return consumeIdent(args);
     return consumeLengthOrPercent(args, cssParserMode, ValueRangeNonNegative);
 }
 
-static RawPtr<CSSBasicShapeCircleValue> consumeBasicShapeCircle(CSSParserTokenRange& args, const CSSParserContext& context)
+static CSSBasicShapeCircleValue* consumeBasicShapeCircle(CSSParserTokenRange& args, const CSSParserContext& context)
 {
     // spec: https://drafts.csswg.org/css-shapes/#supported-basic-shapes
     // circle( [<shape-radius>]? [at <position>]? )
-    RawPtr<CSSBasicShapeCircleValue> shape = CSSBasicShapeCircleValue::create();
-    if (RawPtr<CSSPrimitiveValue> radius = consumeShapeRadius(args, context.mode()))
-        shape->setRadius(radius.release());
+    CSSBasicShapeCircleValue* shape = CSSBasicShapeCircleValue::create();
+    if (CSSPrimitiveValue* radius = consumeShapeRadius(args, context.mode()))
+        shape->setRadius(radius);
     if (consumeIdent<CSSValueAt>(args)) {
-        RawPtr<CSSValue> centerX = nullptr;
-        RawPtr<CSSValue> centerY = nullptr;
+        CSSValue* centerX = nullptr;
+        CSSValue* centerY = nullptr;
         if (!consumePosition(args, context.mode(), UnitlessQuirk::Forbid, centerX, centerY))
             return nullptr;
         shape->setCenterX(centerX);
         shape->setCenterY(centerY);
     }
-    return shape.release();
+    return shape;
 }
 
-static RawPtr<CSSBasicShapeEllipseValue> consumeBasicShapeEllipse(CSSParserTokenRange& args, const CSSParserContext& context)
+static CSSBasicShapeEllipseValue* consumeBasicShapeEllipse(CSSParserTokenRange& args, const CSSParserContext& context)
 {
     // spec: https://drafts.csswg.org/css-shapes/#supported-basic-shapes
     // ellipse( [<shape-radius>{2}]? [at <position>]? )
-    RawPtr<CSSBasicShapeEllipseValue> shape = CSSBasicShapeEllipseValue::create();
-    if (RawPtr<CSSPrimitiveValue> radiusX = consumeShapeRadius(args, context.mode())) {
+    CSSBasicShapeEllipseValue* shape = CSSBasicShapeEllipseValue::create();
+    if (CSSPrimitiveValue* radiusX = consumeShapeRadius(args, context.mode())) {
         shape->setRadiusX(radiusX);
-        if (RawPtr<CSSPrimitiveValue> radiusY = consumeShapeRadius(args, context.mode()))
+        if (CSSPrimitiveValue* radiusY = consumeShapeRadius(args, context.mode()))
             shape->setRadiusY(radiusY);
     }
     if (consumeIdent<CSSValueAt>(args)) {
-        RawPtr<CSSValue> centerX = nullptr;
-        RawPtr<CSSValue> centerY = nullptr;
+        CSSValue* centerX = nullptr;
+        CSSValue* centerY = nullptr;
         if (!consumePosition(args, context.mode(), UnitlessQuirk::Forbid, centerX, centerY))
             return nullptr;
         shape->setCenterX(centerX);
         shape->setCenterY(centerY);
     }
-    return shape.release();
+    return shape;
 }
 
-static RawPtr<CSSBasicShapePolygonValue> consumeBasicShapePolygon(CSSParserTokenRange& args, const CSSParserContext& context)
+static CSSBasicShapePolygonValue* consumeBasicShapePolygon(CSSParserTokenRange& args, const CSSParserContext& context)
 {
-    RawPtr<CSSBasicShapePolygonValue> shape = CSSBasicShapePolygonValue::create();
+    CSSBasicShapePolygonValue* shape = CSSBasicShapePolygonValue::create();
     if (identMatches<CSSValueEvenodd, CSSValueNonzero>(args.peek().id())) {
         shape->setWindRule(args.consumeIncludingWhitespace().id() == CSSValueEvenodd ? RULE_EVENODD : RULE_NONZERO);
         if (!consumeCommaIncludingWhitespace(args))
@@ -2486,18 +2498,18 @@
     }
 
     do {
-        RawPtr<CSSPrimitiveValue> xLength = consumeLengthOrPercent(args, context.mode(), ValueRangeAll);
+        CSSPrimitiveValue* xLength = consumeLengthOrPercent(args, context.mode(), ValueRangeAll);
         if (!xLength)
             return nullptr;
-        RawPtr<CSSPrimitiveValue> yLength = consumeLengthOrPercent(args, context.mode(), ValueRangeAll);
+        CSSPrimitiveValue* yLength = consumeLengthOrPercent(args, context.mode(), ValueRangeAll);
         if (!yLength)
             return nullptr;
-        shape->appendPoint(xLength.release(), yLength.release());
+        shape->appendPoint(xLength, yLength);
     } while (consumeCommaIncludingWhitespace(args));
-    return shape.release();
+    return shape;
 }
 
-static void complete4Sides(RawPtr<CSSPrimitiveValue> side[4])
+static void complete4Sides(CSSPrimitiveValue* side[4])
 {
     if (side[3])
         return;
@@ -2509,7 +2521,7 @@
     side[3] = side[1];
 }
 
-static bool consumeRadii(RawPtr<CSSPrimitiveValue> horizontalRadii[4], RawPtr<CSSPrimitiveValue> verticalRadii[4], CSSParserTokenRange& range, CSSParserMode cssParserMode, bool useLegacyParsing)
+static bool consumeRadii(CSSPrimitiveValue* horizontalRadii[4], CSSPrimitiveValue* verticalRadii[4], CSSParserTokenRange& range, CSSParserMode cssParserMode, bool useLegacyParsing)
 {
 #if ENABLE(OILPAN)
     // Unconditionally zero initialize the arrays of raw pointers.
@@ -2551,44 +2563,45 @@
     return true;
 }
 
-static RawPtr<CSSBasicShapeInsetValue> consumeBasicShapeInset(CSSParserTokenRange& args, const CSSParserContext& context)
+static CSSBasicShapeInsetValue* consumeBasicShapeInset(CSSParserTokenRange& args, const CSSParserContext& context)
 {
-    RawPtr<CSSBasicShapeInsetValue> shape = CSSBasicShapeInsetValue::create();
-    RawPtr<CSSPrimitiveValue> top = consumeLengthOrPercent(args, context.mode(), ValueRangeAll);
+    CSSBasicShapeInsetValue* shape = CSSBasicShapeInsetValue::create();
+    CSSPrimitiveValue* top = consumeLengthOrPercent(args, context.mode(), ValueRangeAll);
     if (!top)
         return nullptr;
-    RawPtr<CSSPrimitiveValue> right = nullptr;
-    RawPtr<CSSPrimitiveValue> bottom = nullptr;
-    RawPtr<CSSPrimitiveValue> left = nullptr;
-    if ((right = consumeLengthOrPercent(args, context.mode(), ValueRangeAll))) {
-        if ((bottom = consumeLengthOrPercent(args, context.mode(), ValueRangeAll)))
+    CSSPrimitiveValue* right = consumeLengthOrPercent(args, context.mode(), ValueRangeAll);
+    CSSPrimitiveValue* bottom = nullptr;
+    CSSPrimitiveValue* left = nullptr;
+    if (right) {
+        bottom = consumeLengthOrPercent(args, context.mode(), ValueRangeAll);
+        if (bottom)
             left = consumeLengthOrPercent(args, context.mode(), ValueRangeAll);
     }
     if (left)
-        shape->updateShapeSize4Values(top.get(), right.get(), bottom.get(), left.get());
+        shape->updateShapeSize4Values(top, right, bottom, left);
     else if (bottom)
-        shape->updateShapeSize3Values(top.get(), right.get(), bottom.get());
+        shape->updateShapeSize3Values(top, right, bottom);
     else if (right)
-        shape->updateShapeSize2Values(top.get(), right.get());
+        shape->updateShapeSize2Values(top, right);
     else
-        shape->updateShapeSize1Value(top.get());
+        shape->updateShapeSize1Value(top);
 
     if (consumeIdent<CSSValueRound>(args)) {
-        RawPtr<CSSPrimitiveValue> horizontalRadii[4];
-        RawPtr<CSSPrimitiveValue> verticalRadii[4];
+        CSSPrimitiveValue* horizontalRadii[4];
+        CSSPrimitiveValue* verticalRadii[4];
         if (!consumeRadii(horizontalRadii, verticalRadii, args, context.mode(), false))
             return nullptr;
-        shape->setTopLeftRadius(CSSValuePair::create(horizontalRadii[0].release(), verticalRadii[0].release(), CSSValuePair::DropIdenticalValues));
-        shape->setTopRightRadius(CSSValuePair::create(horizontalRadii[1].release(), verticalRadii[1].release(), CSSValuePair::DropIdenticalValues));
-        shape->setBottomRightRadius(CSSValuePair::create(horizontalRadii[2].release(), verticalRadii[2].release(), CSSValuePair::DropIdenticalValues));
-        shape->setBottomLeftRadius(CSSValuePair::create(horizontalRadii[3].release(), verticalRadii[3].release(), CSSValuePair::DropIdenticalValues));
+        shape->setTopLeftRadius(CSSValuePair::create(horizontalRadii[0], verticalRadii[0], CSSValuePair::DropIdenticalValues));
+        shape->setTopRightRadius(CSSValuePair::create(horizontalRadii[1], verticalRadii[1], CSSValuePair::DropIdenticalValues));
+        shape->setBottomRightRadius(CSSValuePair::create(horizontalRadii[2], verticalRadii[2], CSSValuePair::DropIdenticalValues));
+        shape->setBottomLeftRadius(CSSValuePair::create(horizontalRadii[3], verticalRadii[3], CSSValuePair::DropIdenticalValues));
     }
-    return shape.release();
+    return shape;
 }
 
-static RawPtr<CSSValue> consumeBasicShape(CSSParserTokenRange& range, const CSSParserContext& context)
+static CSSValue* consumeBasicShape(CSSParserTokenRange& range, const CSSParserContext& context)
 {
-    RawPtr<CSSValue> shape = nullptr;
+    CSSValue* shape = nullptr;
     if (range.peek().type() != FunctionToken)
         return nullptr;
     CSSValueID id = range.peek().functionId();
@@ -2605,10 +2618,10 @@
     if (!shape || !args.atEnd())
         return nullptr;
     range = rangeCopy;
-    return shape.release();
+    return shape;
 }
 
-static RawPtr<CSSValue> consumeClipPath(CSSParserTokenRange& range, const CSSParserContext& context)
+static CSSValue* consumeClipPath(CSSParserTokenRange& range, const CSSParserContext& context)
 {
     if (range.peek().id() == CSSValueNone)
         return consumeIdent(range);
@@ -2618,26 +2631,26 @@
     return consumeBasicShape(range, context);
 }
 
-static RawPtr<CSSValue> consumeShapeOutside(CSSParserTokenRange& range, const CSSParserContext& context)
+static CSSValue* consumeShapeOutside(CSSParserTokenRange& range, const CSSParserContext& context)
 {
-    if (RawPtr<CSSValue> imageValue = consumeImageOrNone(range, context))
-        return imageValue.release();
-    RawPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
-    if (RawPtr<CSSValue> boxValue = consumeIdent<CSSValueContentBox, CSSValuePaddingBox, CSSValueBorderBox, CSSValueMarginBox>(range))
-        list->append(boxValue.release());
-    if (RawPtr<CSSValue> shapeValue = consumeBasicShape(range, context)) {
-        list->append(shapeValue.release());
+    if (CSSValue* imageValue = consumeImageOrNone(range, context))
+        return imageValue;
+    CSSValueList* list = CSSValueList::createSpaceSeparated();
+    if (CSSValue* boxValue = consumeIdent<CSSValueContentBox, CSSValuePaddingBox, CSSValueBorderBox, CSSValueMarginBox>(range))
+        list->append(boxValue);
+    if (CSSValue* shapeValue = consumeBasicShape(range, context)) {
+        list->append(shapeValue);
         if (list->length() < 2) {
-            if (RawPtr<CSSValue> boxValue = consumeIdent<CSSValueContentBox, CSSValuePaddingBox, CSSValueBorderBox, CSSValueMarginBox>(range))
-                list->append(boxValue.release());
+            if (CSSValue* boxValue = consumeIdent<CSSValueContentBox, CSSValuePaddingBox, CSSValueBorderBox, CSSValueMarginBox>(range))
+                list->append(boxValue);
         }
     }
     if (!list->length())
         return nullptr;
-    return list.release();
+    return list;
 }
 
-static RawPtr<CSSValue> consumeContentDistributionOverflowPosition(CSSParserTokenRange& range)
+static CSSValue* consumeContentDistributionOverflowPosition(CSSParserTokenRange& range)
 {
     if (identMatches<CSSValueNormal, CSSValueBaseline, CSSValueLastBaseline>(range.peek().id()))
         return CSSContentDistributionValue::create(CSSValueInvalid, range.consumeIncludingWhitespace().id(), CSSValueInvalid);
@@ -2676,32 +2689,32 @@
     return CSSContentDistributionValue::create(distribution, position, overflow);
 }
 
-static RawPtr<CSSPrimitiveValue> consumeBorderImageRepeatKeyword(CSSParserTokenRange& range)
+static CSSPrimitiveValue* consumeBorderImageRepeatKeyword(CSSParserTokenRange& range)
 {
     return consumeIdent<CSSValueStretch, CSSValueRepeat, CSSValueSpace, CSSValueRound>(range);
 }
 
-static RawPtr<CSSValue> consumeBorderImageRepeat(CSSParserTokenRange& range)
+static CSSValue* consumeBorderImageRepeat(CSSParserTokenRange& range)
 {
-    RawPtr<CSSPrimitiveValue> horizontal = consumeBorderImageRepeatKeyword(range);
+    CSSPrimitiveValue* horizontal = consumeBorderImageRepeatKeyword(range);
     if (!horizontal)
         return nullptr;
-    RawPtr<CSSPrimitiveValue> vertical = consumeBorderImageRepeatKeyword(range);
+    CSSPrimitiveValue* vertical = consumeBorderImageRepeatKeyword(range);
     if (!vertical)
         vertical = horizontal;
-    return CSSValuePair::create(horizontal.release(), vertical.release(), CSSValuePair::DropIdenticalValues);
+    return CSSValuePair::create(horizontal, vertical, CSSValuePair::DropIdenticalValues);
 }
 
-static RawPtr<CSSValue> consumeBorderImageSlice(CSSPropertyID property, CSSParserTokenRange& range, CSSParserMode cssParserMode)
+static CSSValue* consumeBorderImageSlice(CSSPropertyID property, CSSParserTokenRange& range, CSSParserMode cssParserMode)
 {
     bool fill = consumeIdent<CSSValueFill>(range);
-    RawPtr<CSSPrimitiveValue> slices[4];
+    CSSPrimitiveValue* slices[4];
 #if ENABLE(OILPAN)
     // Unconditionally zero initialize the arrays of raw pointers.
     memset(slices, 0, 4 * sizeof(slices[0]));
 #endif
     for (size_t index = 0; index < 4; ++index) {
-        RawPtr<CSSPrimitiveValue> value = consumePercent(range, ValueRangeNonNegative);
+        CSSPrimitiveValue* value = consumePercent(range, ValueRangeNonNegative);
         if (!value)
             value = consumeNumber(range, ValueRangeNonNegative);
         if (!value)
@@ -2720,17 +2733,17 @@
     // FIXME: What do we do with -webkit-box-reflect and -webkit-mask-box-image? Probably just have to leave them filling...
     if (property == CSSPropertyWebkitBorderImage || property == CSSPropertyWebkitMaskBoxImage || property == CSSPropertyWebkitBoxReflect)
         fill = true;
-    return CSSBorderImageSliceValue::create(CSSQuadValue::create(slices[0].release(), slices[1].release(), slices[2].release(), slices[3].release(), CSSQuadValue::SerializeAsQuad), fill);
+    return CSSBorderImageSliceValue::create(CSSQuadValue::create(slices[0], slices[1], slices[2], slices[3], CSSQuadValue::SerializeAsQuad), fill);
 }
 
-static RawPtr<CSSValue> consumeBorderImageOutset(CSSParserTokenRange& range)
+static CSSValue* consumeBorderImageOutset(CSSParserTokenRange& range)
 {
-    RawPtr<CSSPrimitiveValue> outsets[4];
+    CSSPrimitiveValue* outsets[4];
 #if ENABLE(OILPAN)
     // Unconditionally zero initialize the arrays of raw pointers.
     memset(outsets, 0, 4 * sizeof(outsets[0]));
 #endif
-    RawPtr<CSSPrimitiveValue> value = nullptr;
+    CSSPrimitiveValue* value = nullptr;
     for (size_t index = 0; index < 4; ++index) {
         value = consumeNumber(range, ValueRangeNonNegative);
         if (!value)
@@ -2742,17 +2755,17 @@
     if (!outsets[0])
         return nullptr;
     complete4Sides(outsets);
-    return CSSQuadValue::create(outsets[0].release(), outsets[1].release(), outsets[2].release(), outsets[3].release(), CSSQuadValue::SerializeAsQuad);
+    return CSSQuadValue::create(outsets[0], outsets[1], outsets[2], outsets[3], CSSQuadValue::SerializeAsQuad);
 }
 
-static RawPtr<CSSValue> consumeBorderImageWidth(CSSParserTokenRange& range)
+static CSSValue* consumeBorderImageWidth(CSSParserTokenRange& range)
 {
-    RawPtr<CSSPrimitiveValue> widths[4];
+    CSSPrimitiveValue* widths[4];
 #if ENABLE(OILPAN)
     // Unconditionally zero initialize the arrays of raw pointers.
     memset(widths, 0, 4 * sizeof(widths[0]));
 #endif
-    RawPtr<CSSPrimitiveValue> value = nullptr;
+    CSSPrimitiveValue* value = nullptr;
     for (size_t index = 0; index < 4; ++index) {
         value = consumeNumber(range, ValueRangeNonNegative);
         if (!value)
@@ -2766,28 +2779,39 @@
     if (!widths[0])
         return nullptr;
     complete4Sides(widths);
-    return CSSQuadValue::create(widths[0].release(), widths[1].release(), widths[2].release(), widths[3].release(), CSSQuadValue::SerializeAsQuad);
+    return CSSQuadValue::create(widths[0], widths[1], widths[2], widths[3], CSSQuadValue::SerializeAsQuad);
 }
 
-static bool consumeBorderImageComponents(CSSPropertyID property, CSSParserTokenRange& range, const CSSParserContext& context, RawPtr<CSSValue>& source,
-    RawPtr<CSSValue>& slice, RawPtr<CSSValue>& width, RawPtr<CSSValue>& outset, RawPtr<CSSValue>& repeat)
+static bool consumeBorderImageComponents(CSSPropertyID property, CSSParserTokenRange& range, const CSSParserContext& context, CSSValue*& source,
+    CSSValue*& slice, CSSValue*& width, CSSValue*& outset, CSSValue*& repeat)
 {
     do {
-        if (!source && (source = consumeImageOrNone(range, context)))
-            continue;
-        if (!repeat && (repeat = consumeBorderImageRepeat(range)))
-            continue;
-        if (!slice && (slice = consumeBorderImageSlice(property, range, context.mode()))) {
-            ASSERT(!width && !outset);
-            if (consumeSlashIncludingWhitespace(range)) {
-                width = consumeBorderImageWidth(range);
+        if (!source) {
+            source = consumeImageOrNone(range, context);
+            if (source)
+                continue;
+        }
+        if (!repeat) {
+            repeat = consumeBorderImageRepeat(range);
+            if (repeat)
+                continue;
+        }
+        if (!slice) {
+            slice = consumeBorderImageSlice(property, range, context.mode());
+            if (slice) {
+                ASSERT(!width && !outset);
                 if (consumeSlashIncludingWhitespace(range)) {
-                    outset = consumeBorderImageOutset(range);
-                    if (!outset)
+                    width = consumeBorderImageWidth(range);
+                    if (consumeSlashIncludingWhitespace(range)) {
+                        outset = consumeBorderImageOutset(range);
+                        if (!outset)
+                            return false;
+                    } else if (!width) {
                         return false;
-                } else if (!width) {
-                    return false;
+                    }
                 }
+            } else {
+                return false;
             }
         } else {
             return false;
@@ -2796,25 +2820,25 @@
     return true;
 }
 
-static RawPtr<CSSValue> consumeWebkitBorderImage(CSSPropertyID property, CSSParserTokenRange& range, const CSSParserContext& context)
+static CSSValue* consumeWebkitBorderImage(CSSPropertyID property, CSSParserTokenRange& range, const CSSParserContext& context)
 {
-    RawPtr<CSSValue> source = nullptr;
-    RawPtr<CSSValue> slice = nullptr;
-    RawPtr<CSSValue> width = nullptr;
-    RawPtr<CSSValue> outset = nullptr;
-    RawPtr<CSSValue> repeat = nullptr;
+    CSSValue* source = nullptr;
+    CSSValue* slice = nullptr;
+    CSSValue* width = nullptr;
+    CSSValue* outset = nullptr;
+    CSSValue* repeat = nullptr;
     if (consumeBorderImageComponents(property, range, context, source, slice, width, outset, repeat))
         return createBorderImageValue(source, slice, width, outset, repeat);
     return nullptr;
 }
 
-static RawPtr<CSSValue> consumeReflect(CSSParserTokenRange& range, const CSSParserContext& context)
+static CSSValue* consumeReflect(CSSParserTokenRange& range, const CSSParserContext& context)
 {
-    RawPtr<CSSPrimitiveValue> direction = consumeIdent<CSSValueAbove, CSSValueBelow, CSSValueLeft, CSSValueRight>(range);
+    CSSPrimitiveValue* direction = consumeIdent<CSSValueAbove, CSSValueBelow, CSSValueLeft, CSSValueRight>(range);
     if (!direction)
         return nullptr;
 
-    RawPtr<CSSPrimitiveValue> offset = nullptr;
+    CSSPrimitiveValue* offset = nullptr;
     if (range.atEnd()) {
         offset = cssValuePool().createValue(0, CSSPrimitiveValue::UnitType::Pixels);
     } else {
@@ -2823,35 +2847,35 @@
             return nullptr;
     }
 
-    RawPtr<CSSValue> mask = nullptr;
+    CSSValue* mask = nullptr;
     if (!range.atEnd()) {
         mask = consumeWebkitBorderImage(CSSPropertyWebkitBoxReflect, range, context);
         if (!mask)
             return nullptr;
     }
-    return CSSReflectValue::create(direction.release(), offset.release(), mask.release());
+    return CSSReflectValue::create(direction, offset, mask);
 }
 
-static RawPtr<CSSValue> consumeFontSizeAdjust(CSSParserTokenRange& range)
+static CSSValue* consumeFontSizeAdjust(CSSParserTokenRange& range)
 {
     if (range.peek().id() == CSSValueNone)
         return consumeIdent(range);
     return consumeNumber(range, ValueRangeNonNegative);
 }
 
-static RawPtr<CSSValue> consumeImageOrientation(CSSParserTokenRange& range)
+static CSSValue* consumeImageOrientation(CSSParserTokenRange& range)
 {
     if (range.peek().id() == CSSValueFromImage)
         return consumeIdent(range);
     if (range.peek().type() != NumberToken) {
-        RawPtr<CSSPrimitiveValue> angle = consumeAngle(range);
+        CSSPrimitiveValue* angle = consumeAngle(range);
         if (angle && angle->getDoubleValue() == 0)
             return angle;
     }
     return nullptr;
 }
 
-static RawPtr<CSSValue> consumeBackgroundBlendMode(CSSParserTokenRange& range)
+static CSSValue* consumeBackgroundBlendMode(CSSParserTokenRange& range)
 {
     CSSValueID id = range.peek().id();
     if (id == CSSValueNormal || id == CSSValueOverlay || (id >= CSSValueMultiply && id <= CSSValueLuminosity))
@@ -2859,47 +2883,47 @@
     return nullptr;
 }
 
-static RawPtr<CSSValue> consumeBackgroundAttachment(CSSParserTokenRange& range)
+static CSSValue* consumeBackgroundAttachment(CSSParserTokenRange& range)
 {
     return consumeIdent<CSSValueScroll, CSSValueFixed, CSSValueLocal>(range);
 }
 
-static RawPtr<CSSValue> consumeBackgroundBox(CSSParserTokenRange& range)
+static CSSValue* consumeBackgroundBox(CSSParserTokenRange& range)
 {
     return consumeIdent<CSSValueBorderBox, CSSValuePaddingBox, CSSValueContentBox>(range);
 }
 
-static RawPtr<CSSValue> consumeBackgroundComposite(CSSParserTokenRange& range)
+static CSSValue* consumeBackgroundComposite(CSSParserTokenRange& range)
 {
     return consumeIdentRange(range, CSSValueClear, CSSValuePlusLighter);
 }
 
-static RawPtr<CSSValue> consumeMaskSourceType(CSSParserTokenRange& range)
+static CSSValue* consumeMaskSourceType(CSSParserTokenRange& range)
 {
     ASSERT(RuntimeEnabledFeatures::cssMaskSourceTypeEnabled());
     return consumeIdent<CSSValueAuto, CSSValueAlpha, CSSValueLuminance>(range);
 }
 
-static RawPtr<CSSValue> consumePrefixedBackgroundBox(CSSPropertyID property, CSSParserTokenRange& range, const CSSParserContext& context)
+static CSSValue* consumePrefixedBackgroundBox(CSSPropertyID property, CSSParserTokenRange& range, const CSSParserContext& context)
 {
     // The values 'border', 'padding' and 'content' are deprecated and do not apply to the version of the property that has the -webkit- prefix removed.
-    if (RawPtr<CSSValue> value = consumeIdentRange(range, CSSValueBorder, CSSValuePaddingBox))
-        return value.release();
+    if (CSSValue* value = consumeIdentRange(range, CSSValueBorder, CSSValuePaddingBox))
+        return value;
     if ((property == CSSPropertyWebkitBackgroundClip || property == CSSPropertyWebkitMaskClip) && range.peek().id() == CSSValueText)
         return consumeIdent(range);
     return nullptr;
 }
 
-static RawPtr<CSSValue> consumeBackgroundSize(CSSPropertyID unresolvedProperty, CSSParserTokenRange& range, CSSParserMode mode)
+static CSSValue* consumeBackgroundSize(CSSPropertyID unresolvedProperty, CSSParserTokenRange& range, CSSParserMode mode)
 {
     if (identMatches<CSSValueContain, CSSValueCover>(range.peek().id()))
         return consumeIdent(range);
 
-    RawPtr<CSSPrimitiveValue> horizontal = consumeIdent<CSSValueAuto>(range);
+    CSSPrimitiveValue* horizontal = consumeIdent<CSSValueAuto>(range);
     if (!horizontal)
         horizontal = consumeLengthOrPercent(range, mode, ValueRangeAll, UnitlessQuirk::Forbid);
 
-    RawPtr<CSSPrimitiveValue> vertical = nullptr;
+    CSSPrimitiveValue* vertical = nullptr;
     if (!range.atEnd()) {
         if (range.peek().id() == CSSValueAuto) // `auto' is the default
             range.consumeIncludingWhitespace();
@@ -2911,10 +2935,10 @@
     }
     if (!vertical)
         return horizontal;
-    return CSSValuePair::create(horizontal.release(), vertical.release(), CSSValuePair::KeepIdenticalValues);
+    return CSSValuePair::create(horizontal, vertical, CSSValuePair::KeepIdenticalValues);
 }
 
-static RawPtr<CSSValue> consumeBackgroundComponent(CSSPropertyID unresolvedProperty, CSSParserTokenRange& range, const CSSParserContext& context)
+static CSSValue* consumeBackgroundComponent(CSSPropertyID unresolvedProperty, CSSParserTokenRange& range, const CSSParserContext& context)
 {
     switch (unresolvedProperty) {
     case CSSPropertyBackgroundClip:
@@ -2955,34 +2979,34 @@
     return nullptr;
 }
 
-static void addBackgroundValue(RawPtr<CSSValue>& list, RawPtr<CSSValue> value)
+static void addBackgroundValue(CSSValue*& list, CSSValue* value)
 {
     if (list) {
         if (!list->isBaseValueList()) {
-            RawPtr<CSSValue> firstValue = list.release();
+            CSSValue* firstValue = list;
             list = CSSValueList::createCommaSeparated();
-            toCSSValueList(list.get())->append(firstValue.release());
+            toCSSValueList(list)->append(firstValue);
         }
-        toCSSValueList(list.get())->append(value);
+        toCSSValueList(list)->append(value);
     } else {
         // To conserve memory we don't actually wrap a single value in a list.
         list = value;
     }
 }
 
-static RawPtr<CSSValue> consumeCommaSeparatedBackgroundComponent(CSSPropertyID unresolvedProperty, CSSParserTokenRange& range, const CSSParserContext& context)
+static CSSValue* consumeCommaSeparatedBackgroundComponent(CSSPropertyID unresolvedProperty, CSSParserTokenRange& range, const CSSParserContext& context)
 {
-    RawPtr<CSSValue> result = nullptr;
+    CSSValue* result = nullptr;
     do {
-        RawPtr<CSSValue> value = consumeBackgroundComponent(unresolvedProperty, range, context);
+        CSSValue* value = consumeBackgroundComponent(unresolvedProperty, range, context);
         if (!value)
             return nullptr;
         addBackgroundValue(result, value);
     } while (consumeCommaIncludingWhitespace(range));
-    return result.release();
+    return result;
 }
 
-static RawPtr<CSSPrimitiveValue> consumeSelfPositionKeyword(CSSParserTokenRange& range)
+static CSSPrimitiveValue* consumeSelfPositionKeyword(CSSParserTokenRange& range)
 {
     CSSValueID id = range.peek().id();
     if (id == CSSValueStart || id == CSSValueEnd || id == CSSValueCenter
@@ -2992,66 +3016,72 @@
     return nullptr;
 }
 
-static RawPtr<CSSValue> consumeSelfPositionOverflowPosition(CSSParserTokenRange& range)
+static CSSValue* consumeSelfPositionOverflowPosition(CSSParserTokenRange& range)
 {
     if (identMatches<CSSValueAuto, CSSValueStretch, CSSValueBaseline, CSSValueLastBaseline>(range.peek().id()))
         return consumeIdent(range);
 
-    RawPtr<CSSPrimitiveValue> overflowPosition = consumeIdent<CSSValueUnsafe, CSSValueSafe>(range);
-    RawPtr<CSSPrimitiveValue> selfPosition = consumeSelfPositionKeyword(range);
+    CSSPrimitiveValue* overflowPosition = consumeIdent<CSSValueUnsafe, CSSValueSafe>(range);
+    CSSPrimitiveValue* selfPosition = consumeSelfPositionKeyword(range);
     if (!selfPosition)
         return nullptr;
     if (!overflowPosition)
         overflowPosition = consumeIdent<CSSValueUnsafe, CSSValueSafe>(range);
     if (overflowPosition)
-        return CSSValuePair::create(selfPosition.release(), overflowPosition, CSSValuePair::DropIdenticalValues);
-    return selfPosition.release();
+        return CSSValuePair::create(selfPosition, overflowPosition, CSSValuePair::DropIdenticalValues);
+    return selfPosition;
 }
 
-static RawPtr<CSSValue> consumeJustifyItems(CSSParserTokenRange& range)
+static CSSValue* consumeJustifyItems(CSSParserTokenRange& range)
 {
     CSSParserTokenRange rangeCopy = range;
-    RawPtr<CSSPrimitiveValue> legacy = consumeIdent<CSSValueLegacy>(rangeCopy);
-    RawPtr<CSSPrimitiveValue> positionKeyword = consumeIdent<CSSValueCenter, CSSValueLeft, CSSValueRight>(rangeCopy);
+    CSSPrimitiveValue* legacy = consumeIdent<CSSValueLegacy>(rangeCopy);
+    CSSPrimitiveValue* positionKeyword = consumeIdent<CSSValueCenter, CSSValueLeft, CSSValueRight>(rangeCopy);
     if (!legacy)
         legacy = consumeIdent<CSSValueLegacy>(rangeCopy);
     if (legacy && positionKeyword) {
         range = rangeCopy;
-        return CSSValuePair::create(legacy.release(), positionKeyword.release(), CSSValuePair::DropIdenticalValues);
+        return CSSValuePair::create(legacy, positionKeyword, CSSValuePair::DropIdenticalValues);
     }
     return consumeSelfPositionOverflowPosition(range);
 }
 
-static RawPtr<CSSCustomIdentValue> consumeCustomIdentForGridLine(CSSParserTokenRange& range)
+static CSSCustomIdentValue* consumeCustomIdentForGridLine(CSSParserTokenRange& range)
 {
     if (range.peek().id() == CSSValueAuto || range.peek().id() == CSSValueSpan)
         return nullptr;
     return consumeCustomIdent(range);
 }
 
-static RawPtr<CSSValue> consumeGridLine(CSSParserTokenRange& range)
+static CSSValue* consumeGridLine(CSSParserTokenRange& range)
 {
     if (range.peek().id() == CSSValueAuto)
         return consumeIdent(range);
 
-    RawPtr<CSSPrimitiveValue> spanValue = nullptr;
-    RawPtr<CSSCustomIdentValue> gridLineName = nullptr;
-    RawPtr<CSSPrimitiveValue> numericValue = consumeInteger(range);
+    CSSPrimitiveValue* spanValue = nullptr;
+    CSSCustomIdentValue* gridLineName = nullptr;
+    CSSPrimitiveValue* numericValue = consumeInteger(range);
     if (numericValue) {
         gridLineName = consumeCustomIdentForGridLine(range);
         spanValue = consumeIdent<CSSValueSpan>(range);
-    } else if ((spanValue = consumeIdent<CSSValueSpan>(range))) {
-        numericValue = consumeInteger(range);
-        gridLineName = consumeCustomIdentForGridLine(range);
-        if (!numericValue)
-            numericValue = consumeInteger(range);
-    } else if ((gridLineName = consumeCustomIdentForGridLine(range))) {
-        numericValue = consumeInteger(range);
-        spanValue = consumeIdent<CSSValueSpan>(range);
-        if (!spanValue && !numericValue)
-            return gridLineName.release();
     } else {
-        return nullptr;
+        spanValue = consumeIdent<CSSValueSpan>(range);
+        if (spanValue) {
+            numericValue = consumeInteger(range);
+            gridLineName = consumeCustomIdentForGridLine(range);
+            if (!numericValue)
+                numericValue = consumeInteger(range);
+        } else {
+            gridLineName = consumeCustomIdentForGridLine(range);
+            if (gridLineName) {
+                numericValue = consumeInteger(range);
+                spanValue = consumeIdent<CSSValueSpan>(range);
+                if (!spanValue && !numericValue)
+                    return gridLineName;
+            } else {
+                return nullptr;
+            }
+        }
     }
 
     if (spanValue && numericValue && numericValue->getIntValue() < 0)
@@ -3059,18 +3089,18 @@
     if (numericValue && numericValue->getIntValue() == 0)
         return nullptr; // An <integer> value of zero makes the declaration invalid.
 
-    RawPtr<CSSValueList> values = CSSValueList::createSpaceSeparated();
+    CSSValueList* values = CSSValueList::createSpaceSeparated();
     if (spanValue)
-        values->append(spanValue.release());
+        values->append(spanValue);
     if (numericValue)
-        values->append(numericValue.release());
+        values->append(numericValue);
     if (gridLineName)
-        values->append(gridLineName.release());
+        values->append(gridLineName);
     ASSERT(values->length());
-    return values.release();
+    return values;
 }
 
-static RawPtr<CSSPrimitiveValue> consumeGridBreadth(CSSParserTokenRange& range, CSSParserMode cssParserMode, TrackSizeRestriction restriction = AllowAll)
+static CSSPrimitiveValue* consumeGridBreadth(CSSParserTokenRange& range, CSSParserMode cssParserMode, TrackSizeRestriction restriction = AllowAll)
 {
     if (restriction == AllowAll) {
         const CSSParserToken& token = range.peek();
@@ -3085,7 +3115,7 @@
     return consumeLengthOrPercent(range, cssParserMode, ValueRangeNonNegative, UnitlessQuirk::Allow);
 }
 
-static RawPtr<CSSValue> consumeGridTrackSize(CSSParserTokenRange& range, CSSParserMode cssParserMode, TrackSizeRestriction restriction = AllowAll)
+static CSSValue* consumeGridTrackSize(CSSParserTokenRange& range, CSSParserMode cssParserMode, TrackSizeRestriction restriction = AllowAll)
 {
     const CSSParserToken& token = range.peek();
     if (restriction == AllowAll && identMatches<CSSValueAuto>(token.id()))
@@ -3094,33 +3124,33 @@
     if (token.functionId() == CSSValueMinmax) {
         CSSParserTokenRange rangeCopy = range;
         CSSParserTokenRange args = consumeFunction(rangeCopy);
-        RawPtr<CSSPrimitiveValue> minTrackBreadth = consumeGridBreadth(args, cssParserMode, restriction);
+        CSSPrimitiveValue* minTrackBreadth = consumeGridBreadth(args, cssParserMode, restriction);
         if (!minTrackBreadth || !consumeCommaIncludingWhitespace(args))
             return nullptr;
-        RawPtr<CSSPrimitiveValue> maxTrackBreadth = consumeGridBreadth(args, cssParserMode);
+        CSSPrimitiveValue* maxTrackBreadth = consumeGridBreadth(args, cssParserMode);
         if (!maxTrackBreadth || !args.atEnd())
             return nullptr;
         range = rangeCopy;
-        RawPtr<CSSFunctionValue> result = CSSFunctionValue::create(CSSValueMinmax);
-        result->append(minTrackBreadth.release());
-        result->append(maxTrackBreadth.release());
-        return result.release();
+        CSSFunctionValue* result = CSSFunctionValue::create(CSSValueMinmax);
+        result->append(minTrackBreadth);
+        result->append(maxTrackBreadth);
+        return result;
     }
     return consumeGridBreadth(range, cssParserMode, restriction);
 }
 
-static RawPtr<CSSGridLineNamesValue> consumeGridLineNames(CSSParserTokenRange& range)
+static CSSGridLineNamesValue* consumeGridLineNames(CSSParserTokenRange& range)
 {
     CSSParserTokenRange rangeCopy = range;
     if (rangeCopy.consumeIncludingWhitespace().type() != LeftBracketToken)
         return nullptr;
-    RawPtr<CSSGridLineNamesValue> lineNames = CSSGridLineNamesValue::create();
-    while (RawPtr<CSSCustomIdentValue> lineName = consumeCustomIdentForGridLine(rangeCopy))
-        lineNames->append(lineName.release());
+    CSSGridLineNamesValue* lineNames = CSSGridLineNamesValue::create();
+    while (CSSCustomIdentValue* lineName = consumeCustomIdentForGridLine(rangeCopy))
+        lineNames->append(lineName);
     if (rangeCopy.consumeIncludingWhitespace().type() != RightBracketToken)
         return nullptr;
     range = rangeCopy;
-    return lineNames.release();
+    return lineNames;
 }
 
 static bool consumeGridTrackRepeatFunction(CSSParserTokenRange& range, CSSParserMode cssParserMode, CSSValueList& list, bool& isAutoRepeat)
@@ -3130,12 +3160,12 @@
     // because it will be computed later, let's set it to 1.
     size_t repetitions = 1;
     isAutoRepeat = identMatches<CSSValueAutoFill, CSSValueAutoFit>(args.peek().id());
-    RawPtr<CSSValueList> repeatedValues;
+    CSSValueList* repeatedValues;
     if (isAutoRepeat) {
         repeatedValues = CSSGridAutoRepeatValue::create(args.consumeIncludingWhitespace().id());
     } else {
         // TODO(rob.buis): a consumeIntegerRaw would be more efficient here.
-        RawPtr<CSSPrimitiveValue> repetition = consumePositiveInteger(args);
+        CSSPrimitiveValue* repetition = consumePositiveInteger(args);
         if (!repetition)
             return false;
         repetitions = clampTo<size_t>(repetition->getDoubleValue(), 0, kGridMaxTracks);
@@ -3143,30 +3173,30 @@
     }
     if (!consumeCommaIncludingWhitespace(args))
         return false;
-    RawPtr<CSSGridLineNamesValue> lineNames = consumeGridLineNames(args);
+    CSSGridLineNamesValue* lineNames = consumeGridLineNames(args);
     if (lineNames)
-        repeatedValues->append(lineNames.release());
+        repeatedValues->append(lineNames);
 
     size_t numberOfTracks = 0;
     TrackSizeRestriction restriction = isAutoRepeat ? FixedSizeOnly : AllowAll;
     while (!args.atEnd()) {
         if (isAutoRepeat && numberOfTracks)
             return false;
-        RawPtr<CSSValue> trackSize = consumeGridTrackSize(args, cssParserMode, restriction);
+        CSSValue* trackSize = consumeGridTrackSize(args, cssParserMode, restriction);
         if (!trackSize)
             return false;
-        repeatedValues->append(trackSize.release());
+        repeatedValues->append(trackSize);
         ++numberOfTracks;
         lineNames = consumeGridLineNames(args);
         if (lineNames)
-            repeatedValues->append(lineNames.release());
+            repeatedValues->append(lineNames);
     }
     // We should have found at least one <track-size> or else it is not a valid <track-list>.
     if (!numberOfTracks)
         return false;
 
     if (isAutoRepeat) {
-        list.append(repeatedValues.release());
+        list.append(repeatedValues);
     } else {
         // We clamp the repetitions to a multiple of the repeat() track list's size, while staying below the max grid size.
         repetitions = std::min(repetitions, kGridMaxTracks / numberOfTracks);
@@ -3178,12 +3208,12 @@
     return true;
 }
 
-static RawPtr<CSSValue> consumeGridTrackList(CSSParserTokenRange& range, CSSParserMode cssParserMode)
+static CSSValue* consumeGridTrackList(CSSParserTokenRange& range, CSSParserMode cssParserMode)
 {
-    RawPtr<CSSValueList> values = CSSValueList::createSpaceSeparated();
-    RawPtr<CSSGridLineNamesValue> lineNames = consumeGridLineNames(range);
+    CSSValueList* values = CSSValueList::createSpaceSeparated();
+    CSSGridLineNamesValue* lineNames = consumeGridLineNames(range);
     if (lineNames)
-        values->append(lineNames.release());
+        values->append(lineNames);
 
     bool seenAutoRepeat = false;
     // TODO(rob.buis): <line-names> should not be able to directly precede <auto-repeat>.
@@ -3195,30 +3225,30 @@
             if (isAutoRepeat && seenAutoRepeat)
                 return nullptr;
             seenAutoRepeat = seenAutoRepeat || isAutoRepeat;
-        } else if (RawPtr<CSSValue> value = consumeGridTrackSize(range, cssParserMode, seenAutoRepeat ? FixedSizeOnly : AllowAll)) {
-            values->append(value.release());
+        } else if (CSSValue* value = consumeGridTrackSize(range, cssParserMode, seenAutoRepeat ? FixedSizeOnly : AllowAll)) {
+            values->append(value);
         } else {
             return nullptr;
         }
         lineNames = consumeGridLineNames(range);
         if (lineNames)
-            values->append(lineNames.release());
+            values->append(lineNames);
     } while (!range.atEnd() && range.peek().type() != DelimiterToken);
     // <auto-repeat> requires definite minimum track sizes in order to compute the number of repetitions.
     // The above while loop detects those appearances after the <auto-repeat> but not the ones before.
     if (seenAutoRepeat && !allTracksAreFixedSized(*values))
         return nullptr;
-    return values.release();
+    return values;
 }
 
-static RawPtr<CSSValue> consumeGridTemplatesRowsOrColumns(CSSParserTokenRange& range, CSSParserMode cssParserMode)
+static CSSValue* consumeGridTemplatesRowsOrColumns(CSSParserTokenRange& range, CSSParserMode cssParserMode)
 {
     if (range.peek().id() == CSSValueNone)
         return consumeIdent(range);
     return consumeGridTrackList(range, cssParserMode);
 }
 
-static RawPtr<CSSValue> consumeGridTemplateAreas(CSSParserTokenRange& range)
+static CSSValue* consumeGridTemplateAreas(CSSParserTokenRange& range)
 {
     if (range.peek().id() == CSSValueNone)
         return consumeIdent(range);
@@ -3239,7 +3269,7 @@
     return CSSGridTemplateAreasValue::create(gridAreaMap, rowCount, columnCount);
 }
 
-RawPtr<CSSValue> CSSPropertyParser::parseSingleValue(CSSPropertyID unresolvedProperty)
+CSSValue* CSSPropertyParser::parseSingleValue(CSSPropertyID unresolvedProperty)
 {
     CSSPropertyID property = resolveCSSPropertyID(unresolvedProperty);
     if (CSSParserFastPaths::isKeywordPropertyID(property)) {
@@ -3622,19 +3652,19 @@
         CSSParserValueList valueList(m_range);
         if (valueList.size()) {
             m_valueList = &valueList;
-            if (RawPtr<CSSValue> result = legacyParseValue(unresolvedProperty)) {
+            if (CSSValue* result = legacyParseValue(unresolvedProperty)) {
                 while (!m_range.atEnd())
                     m_range.consume();
-                return result.release();
+                return result;
             }
         }
         return nullptr;
     }
 }
 
-static RawPtr<CSSValueList> consumeFontFaceUnicodeRange(CSSParserTokenRange& range)
+static CSSValueList* consumeFontFaceUnicodeRange(CSSParserTokenRange& range)
 {
-    RawPtr<CSSValueList> values = CSSValueList::createCommaSeparated();
+    CSSValueList* values = CSSValueList::createCommaSeparated();
 
     do {
         const CSSParserToken& token = range.consumeIncludingWhitespace();
@@ -3648,19 +3678,19 @@
         values->append(CSSUnicodeRangeValue::create(start, end));
     } while (consumeCommaIncludingWhitespace(range));
 
-    return values.release();
+    return values;
 }
 
-static RawPtr<CSSValue> consumeFontFaceSrcURI(CSSParserTokenRange& range, const CSSParserContext& context)
+static CSSValue* consumeFontFaceSrcURI(CSSParserTokenRange& range, const CSSParserContext& context)
 {
     String url = consumeUrl(range);
     if (url.isNull())
         return nullptr;
-    RawPtr<CSSFontFaceSrcValue> uriValue(CSSFontFaceSrcValue::create(url, context.completeURL(url), context.shouldCheckContentSecurityPolicy()));
+    CSSFontFaceSrcValue* uriValue(CSSFontFaceSrcValue::create(url, context.completeURL(url), context.shouldCheckContentSecurityPolicy()));
     uriValue->setReferrer(context.referrer());
 
     if (range.peek().functionId() != CSSValueFormat)
-        return uriValue.release();
+        return uriValue;
 
     // FIXME: https://drafts.csswg.org/css-fonts says that format() contains a comma-separated list of strings,
     // but CSSFontFaceSrcValue stores only one format. Allowing one format for now.
@@ -3670,10 +3700,10 @@
     if ((arg.type() != StringToken && arg.type() != IdentToken) || !args.atEnd())
         return nullptr;
     uriValue->setFormat(arg.value());
-    return uriValue.release();
+    return uriValue;
 }
 
-static RawPtr<CSSValue> consumeFontFaceSrcLocal(CSSParserTokenRange& range, const CSSParserContext& context)
+static CSSValue* consumeFontFaceSrcLocal(CSSParserTokenRange& range, const CSSParserContext& context)
 {
     CSSParserTokenRange args = consumeFunction(range);
     ContentSecurityPolicyDisposition shouldCheckContentSecurityPolicy = context.shouldCheckContentSecurityPolicy();
@@ -3692,13 +3722,13 @@
     return nullptr;
 }
 
-static RawPtr<CSSValueList> consumeFontFaceSrc(CSSParserTokenRange& range, const CSSParserContext& context)
+static CSSValueList* consumeFontFaceSrc(CSSParserTokenRange& range, const CSSParserContext& context)
 {
-    RawPtr<CSSValueList> values(CSSValueList::createCommaSeparated());
+    CSSValueList* values = CSSValueList::createCommaSeparated();
 
     do {
         const CSSParserToken& token = range.peek();
-        RawPtr<CSSValue> parsedValue = nullptr;
+        CSSValue* parsedValue = nullptr;
         if (token.functionId() == CSSValueLocal)
             parsedValue = consumeFontFaceSrcLocal(range, context);
         else
@@ -3707,12 +3737,12 @@
             return nullptr;
         values->append(parsedValue);
     } while (consumeCommaIncludingWhitespace(range));
-    return values.release();
+    return values;
 }
 
 bool CSSPropertyParser::parseFontFaceDescriptor(CSSPropertyID propId)
 {
-    RawPtr<CSSValue> parsedValue = nullptr;
+    CSSValue* parsedValue = nullptr;
     switch (propId) {
     case CSSPropertyFontFamily:
         if (consumeGenericFamily(m_range))
@@ -3750,7 +3780,7 @@
     if (!parsedValue || !m_range.atEnd())
         return false;
 
-    addProperty(propId, parsedValue.release(), false);
+    addProperty(propId, parsedValue, false);
     return true;
 }
 
@@ -3770,9 +3800,9 @@
     addProperty(CSSPropertyFontStyle, cssValuePool().createIdentifierValue(fontStyle == FontStyleItalic ? CSSValueItalic : CSSValueNormal), important);
     addProperty(CSSPropertyFontWeight, cssValuePool().createValue(fontWeight), important);
     addProperty(CSSPropertyFontSize, cssValuePool().createValue(fontSize, CSSPrimitiveValue::UnitType::Pixels), important);
-    RawPtr<CSSValueList> fontFamilyList = CSSValueList::createCommaSeparated();
+    CSSValueList* fontFamilyList = CSSValueList::createCommaSeparated();
     fontFamilyList->append(cssValuePool().createFontFamilyValue(fontFamily));
-    addProperty(CSSPropertyFontFamily, fontFamilyList.release(), important);
+    addProperty(CSSPropertyFontFamily, fontFamilyList, important);
 
     addProperty(CSSPropertyFontStretch, cssValuePool().createIdentifierValue(CSSValueNormal), important);
     addProperty(CSSPropertyFontVariant, cssValuePool().createIdentifierValue(CSSValueNormal), important);
@@ -3790,10 +3820,10 @@
             return false;
     }
     // Optional font-style, font-variant, font-stretch and font-weight.
-    RawPtr<CSSPrimitiveValue> fontStyle = nullptr;
-    RawPtr<CSSPrimitiveValue> fontVariant = nullptr;
-    RawPtr<CSSPrimitiveValue> fontWeight = nullptr;
-    RawPtr<CSSPrimitiveValue> fontStretch = nullptr;
+    CSSPrimitiveValue* fontStyle = nullptr;
+    CSSPrimitiveValue* fontVariant = nullptr;
+    CSSPrimitiveValue* fontWeight = nullptr;
+    CSSPrimitiveValue* fontStretch = nullptr;
     while (!m_range.atEnd()) {
         CSSValueID id = m_range.peek().id();
         if (!fontStyle && CSSParserFastPaths::isValidKeywordPropertyAndValue(CSSPropertyFontStyle, id)) {
@@ -3820,33 +3850,33 @@
     if (m_range.atEnd())
         return false;
 
-    addProperty(CSSPropertyFontStyle, fontStyle ? fontStyle.release() : cssValuePool().createIdentifierValue(CSSValueNormal), important);
-    addProperty(CSSPropertyFontVariant, fontVariant ? fontVariant.release() : cssValuePool().createIdentifierValue(CSSValueNormal), important);
-    addProperty(CSSPropertyFontWeight, fontWeight ? fontWeight.release() : cssValuePool().createIdentifierValue(CSSValueNormal), important);
-    addProperty(CSSPropertyFontStretch, fontStretch ? fontStretch.release() : cssValuePool().createIdentifierValue(CSSValueNormal), important);
+    addProperty(CSSPropertyFontStyle, fontStyle ? fontStyle : cssValuePool().createIdentifierValue(CSSValueNormal), important);
+    addProperty(CSSPropertyFontVariant, fontVariant ? fontVariant : cssValuePool().createIdentifierValue(CSSValueNormal), important);
+    addProperty(CSSPropertyFontWeight, fontWeight ? fontWeight : cssValuePool().createIdentifierValue(CSSValueNormal), important);
+    addProperty(CSSPropertyFontStretch, fontStretch ? fontStretch : cssValuePool().createIdentifierValue(CSSValueNormal), important);
 
     // Now a font size _must_ come.
-    RawPtr<CSSValue> fontSize = consumeFontSize(m_range, m_context.mode());
+    CSSValue* fontSize = consumeFontSize(m_range, m_context.mode());
     if (!fontSize || m_range.atEnd())
         return false;
 
-    addProperty(CSSPropertyFontSize, fontSize.release(), important);
+    addProperty(CSSPropertyFontSize, fontSize, important);
 
     if (consumeSlashIncludingWhitespace(m_range)) {
-        RawPtr<CSSPrimitiveValue> lineHeight = consumeLineHeight(m_range, m_context.mode());
+        CSSPrimitiveValue* lineHeight = consumeLineHeight(m_range, m_context.mode());
         if (!lineHeight)
             return false;
-        addProperty(CSSPropertyLineHeight, lineHeight.release(), important);
+        addProperty(CSSPropertyLineHeight, lineHeight, important);
     } else {
         addProperty(CSSPropertyLineHeight, cssValuePool().createIdentifierValue(CSSValueNormal), important);
     }
 
     // Font family must come now.
-    RawPtr<CSSValue> parsedFamilyValue = consumeFontFamily(m_range);
+    CSSValue* parsedFamilyValue = consumeFontFamily(m_range);
     if (!parsedFamilyValue)
         return false;
 
-    addProperty(CSSPropertyFontFamily, parsedFamilyValue.release(), important);
+    addProperty(CSSPropertyFontFamily, parsedFamilyValue, important);
 
     // FIXME: http://www.w3.org/TR/2011/WD-css3-fonts-20110324/#font-prop requires that
     // "font-stretch", "font-size-adjust", and "font-kerning" be reset to their initial values
@@ -3856,20 +3886,20 @@
 
 bool CSSPropertyParser::consumeBorderSpacing(bool important)
 {
-    RawPtr<CSSValue> horizontalSpacing = consumeLength(m_range, m_context.mode(), ValueRangeNonNegative, UnitlessQuirk::Allow);
+    CSSValue* horizontalSpacing = consumeLength(m_range, m_context.mode(), ValueRangeNonNegative, UnitlessQuirk::Allow);
     if (!horizontalSpacing)
         return false;
-    RawPtr<CSSValue> verticalSpacing = horizontalSpacing;
+    CSSValue* verticalSpacing = horizontalSpacing;
     if (!m_range.atEnd())
         verticalSpacing = consumeLength(m_range, m_context.mode(), ValueRangeNonNegative, UnitlessQuirk::Allow);
     if (!verticalSpacing || !m_range.atEnd())
         return false;
-    addProperty(CSSPropertyWebkitBorderHorizontalSpacing, horizontalSpacing.release(), important);
-    addProperty(CSSPropertyWebkitBorderVerticalSpacing, verticalSpacing.release(), important);
+    addProperty(CSSPropertyWebkitBorderHorizontalSpacing, horizontalSpacing, important);
+    addProperty(CSSPropertyWebkitBorderVerticalSpacing, verticalSpacing, important);
     return true;
 }
 
-static RawPtr<CSSValue> consumeSingleViewportDescriptor(CSSParserTokenRange& range, CSSPropertyID propId, CSSParserMode cssParserMode)
+static CSSValue* consumeSingleViewportDescriptor(CSSParserTokenRange& range, CSSPropertyID propId, CSSParserMode cssParserMode)
 {
     CSSValueID id = range.peek().id();
     switch (propId) {
@@ -3885,9 +3915,9 @@
     case CSSPropertyZoom: {
         if (id == CSSValueAuto)
             return consumeIdent(range);
-        RawPtr<CSSValue> parsedValue = consumeNumber(range, ValueRangeNonNegative);
+        CSSValue* parsedValue = consumeNumber(range, ValueRangeNonNegative);
         if (parsedValue)
-            return parsedValue.release();
+            return parsedValue;
         return consumePercent(range, ValueRangeNonNegative);
     }
     case CSSPropertyUserZoom:
@@ -3909,29 +3939,29 @@
 
     switch (propId) {
     case CSSPropertyWidth: {
-        RawPtr<CSSValue> minWidth = consumeSingleViewportDescriptor(m_range, CSSPropertyMinWidth, m_context.mode());
+        CSSValue* minWidth = consumeSingleViewportDescriptor(m_range, CSSPropertyMinWidth, m_context.mode());
         if (!minWidth)
             return false;
-        RawPtr<CSSValue> maxWidth = minWidth;
+        CSSValue* maxWidth = minWidth;
         if (!m_range.atEnd())
             maxWidth = consumeSingleViewportDescriptor(m_range, CSSPropertyMaxWidth, m_context.mode());
         if (!maxWidth || !m_range.atEnd())
             return false;
-        addProperty(CSSPropertyMinWidth, minWidth.release(), important);
-        addProperty(CSSPropertyMaxWidth, maxWidth.release(), important);
+        addProperty(CSSPropertyMinWidth, minWidth, important);
+        addProperty(CSSPropertyMaxWidth, maxWidth, important);
         return true;
     }
     case CSSPropertyHeight: {
-        RawPtr<CSSValue> minHeight = consumeSingleViewportDescriptor(m_range, CSSPropertyMinHeight, m_context.mode());
+        CSSValue* minHeight = consumeSingleViewportDescriptor(m_range, CSSPropertyMinHeight, m_context.mode());
         if (!minHeight)
             return false;
-        RawPtr<CSSValue> maxHeight = minHeight;
+        CSSValue* maxHeight = minHeight;
         if (!m_range.atEnd())
             maxHeight = consumeSingleViewportDescriptor(m_range, CSSPropertyMaxHeight, m_context.mode());
         if (!maxHeight || !m_range.atEnd())
             return false;
-        addProperty(CSSPropertyMinHeight, minHeight.release(), important);
-        addProperty(CSSPropertyMaxHeight, maxHeight.release(), important);
+        addProperty(CSSPropertyMinHeight, minHeight, important);
+        addProperty(CSSPropertyMaxHeight, maxHeight, important);
         return true;
     }
     case CSSPropertyMinWidth:
@@ -3943,10 +3973,10 @@
     case CSSPropertyZoom:
     case CSSPropertyUserZoom:
     case CSSPropertyOrientation: {
-        RawPtr<CSSValue> parsedValue = consumeSingleViewportDescriptor(m_range, propId, m_context.mode());
+        CSSValue* parsedValue = consumeSingleViewportDescriptor(m_range, propId, m_context.mode());
         if (!parsedValue || !m_range.atEnd())
             return false;
-        addProperty(propId, parsedValue.release(), important);
+        addProperty(propId, parsedValue, important);
         return true;
     }
     default:
@@ -3954,14 +3984,15 @@
     }
 }
 
-static bool consumeColumnWidthOrCount(CSSParserTokenRange& range, CSSParserMode cssParserMode, RawPtr<CSSValue>& columnWidth, RawPtr<CSSValue>& columnCount)
+static bool consumeColumnWidthOrCount(CSSParserTokenRange& range, CSSParserMode cssParserMode, CSSValue*& columnWidth, CSSValue*& columnCount)
 {
     if (range.peek().id() == CSSValueAuto) {
         consumeIdent(range);
         return true;
     }
     if (!columnWidth) {
-        if ((columnWidth = consumeColumnWidth(range)))
+        columnWidth = consumeColumnWidth(range);
+        if (columnWidth)
             return true;
     }
     if (!columnCount)
@@ -3971,8 +4002,8 @@
 
 bool CSSPropertyParser::consumeColumns(bool important)
 {
-    RawPtr<CSSValue> columnWidth = nullptr;
-    RawPtr<CSSValue> columnCount = nullptr;
+    CSSValue* columnWidth = nullptr;
+    CSSValue* columnCount = nullptr;
     if (!consumeColumnWidthOrCount(m_range, m_context.mode(), columnWidth, columnCount))
         return false;
     consumeColumnWidthOrCount(m_range, m_context.mode(), columnWidth, columnCount);
@@ -3982,15 +4013,15 @@
         columnWidth = cssValuePool().createIdentifierValue(CSSValueAuto);
     if (!columnCount)
         columnCount = cssValuePool().createIdentifierValue(CSSValueAuto);
-    addProperty(CSSPropertyColumnWidth, columnWidth.release(), important);
-    addProperty(CSSPropertyColumnCount, columnCount.release(), important);
+    addProperty(CSSPropertyColumnWidth, columnWidth, important);
+    addProperty(CSSPropertyColumnCount, columnCount, important);
     return true;
 }
 
 bool CSSPropertyParser::consumeShorthandGreedily(const StylePropertyShorthand& shorthand, bool important)
 {
     ASSERT(shorthand.length() <= 6); // Existing shorthands have at most 6 longhands.
-    RawPtr<CSSValue> longhands[6] = { nullptr, nullptr, nullptr, nullptr, nullptr, nullptr };
+    CSSValue* longhands[6] = { nullptr, nullptr, nullptr, nullptr, nullptr, nullptr };
     const CSSPropertyID* shorthandProperties = shorthand.properties();
     do {
         bool foundLonghand = false;
@@ -4007,7 +4038,7 @@
 
     for (size_t i = 0; i < shorthand.length(); ++i) {
         if (longhands[i])
-            addProperty(shorthandProperties[i], longhands[i].release(), important);
+            addProperty(shorthandProperties[i], longhands[i], important);
         else
             addProperty(shorthandProperties[i], cssValuePool().createImplicitInitialValue(), important);
     }
@@ -4019,7 +4050,7 @@
     static const double unsetValue = -1;
     double flexGrow = unsetValue;
     double flexShrink = unsetValue;
-    RawPtr<CSSPrimitiveValue> flexBasis = nullptr;
+    CSSPrimitiveValue* flexBasis = nullptr;
 
     if (m_range.peek().id() == CSSValueNone) {
         flexGrow = 0;
@@ -4070,17 +4101,26 @@
 
 bool CSSPropertyParser::consumeBorder(bool important)
 {
-    RawPtr<CSSValue> width = nullptr;
-    RawPtr<CSSValue> style = nullptr;
-    RawPtr<CSSValue> color = nullptr;
+    CSSValue* width = nullptr;
+    CSSValue* style = nullptr;
+    CSSValue* color = nullptr;
 
     while (!width || !style || !color) {
-        if (!width && (width = consumeLineWidth(m_range, m_context.mode(), UnitlessQuirk::Forbid)))
-            continue;
-        if (!style && (style = parseSingleValue(CSSPropertyBorderLeftStyle)))
-            continue;
-        if (!color && (color = consumeColor(m_range, m_context.mode())))
-            continue;
+        if (!width) {
+            width = consumeLineWidth(m_range, m_context.mode(), UnitlessQuirk::Forbid);
+            if (width)
+                continue;
+        }
+        if (!style) {
+            style = parseSingleValue(CSSPropertyBorderLeftStyle);
+            if (style)
+                continue;
+        }
+        if (!color) {
+            color = consumeColor(m_range, m_context.mode());
+            if (color)
+                continue;
+        }
         break;
     }
 
@@ -4094,9 +4134,9 @@
     if (!color)
         color = cssValuePool().createImplicitInitialValue();
 
-    addExpandedPropertyForValue(CSSPropertyBorderWidth, width.release(), important);
-    addExpandedPropertyForValue(CSSPropertyBorderStyle, style.release(), important);
-    addExpandedPropertyForValue(CSSPropertyBorderColor, color.release(), important);
+    addExpandedPropertyForValue(CSSPropertyBorderWidth, width, important);
+    addExpandedPropertyForValue(CSSPropertyBorderStyle, style, important);
+    addExpandedPropertyForValue(CSSPropertyBorderColor, color, important);
     addExpandedPropertyForValue(CSSPropertyBorderImage, cssValuePool().createImplicitInitialValue(), important);
 
     return m_range.atEnd();
@@ -4106,15 +4146,16 @@
 {
     ASSERT(shorthand.length() == 4);
     const CSSPropertyID* longhands = shorthand.properties();
-    RawPtr<CSSValue> top = parseSingleValue(longhands[0]);
+    CSSValue* top = parseSingleValue(longhands[0]);
     if (!top)
         return false;
 
-    RawPtr<CSSValue> right = nullptr;
-    RawPtr<CSSValue> bottom = nullptr;
-    RawPtr<CSSValue> left = nullptr;
-    if ((right = parseSingleValue(longhands[1]))) {
-        if ((bottom = parseSingleValue(longhands[2])))
+    CSSValue* right = parseSingleValue(longhands[1]);
+    CSSValue* bottom = nullptr;
+    CSSValue* left = nullptr;
+    if (right) {
+        bottom = parseSingleValue(longhands[2]);
+        if (bottom)
             left = parseSingleValue(longhands[3]);
     }
 
@@ -4125,21 +4166,21 @@
     if (!left)
         left = right;
 
-    addProperty(longhands[0], top.release(), important);
-    addProperty(longhands[1], right.release(), important);
-    addProperty(longhands[2], bottom.release(), important);
-    addProperty(longhands[3], left.release(), important);
+    addProperty(longhands[0], top, important);
+    addProperty(longhands[1], right, important);
+    addProperty(longhands[2], bottom, important);
+    addProperty(longhands[3], left, important);
 
     return m_range.atEnd();
 }
 
 bool CSSPropertyParser::consumeBorderImage(CSSPropertyID property, bool important)
 {
-    RawPtr<CSSValue> source = nullptr;
-    RawPtr<CSSValue> slice = nullptr;
-    RawPtr<CSSValue> width = nullptr;
-    RawPtr<CSSValue> outset = nullptr;
-    RawPtr<CSSValue> repeat = nullptr;
+    CSSValue* source = nullptr;
+    CSSValue* slice = nullptr;
+    CSSValue* width = nullptr;
+    CSSValue* outset = nullptr;
+    CSSValue* repeat = nullptr;
     if (consumeBorderImageComponents(property, m_range, m_context, source, slice, width, outset, repeat)) {
         switch (property) {
         case CSSPropertyWebkitMaskBoxImage:
@@ -4204,7 +4245,7 @@
     // The fragmentation spec says that page-break-(after|before|inside) are to be treated as
     // shorthands for their break-(after|before|inside) counterparts. We'll do the same for the
     // non-standard properties -webkit-column-break-(after|before|inside).
-    RawPtr<CSSPrimitiveValue> keyword = consumeIdent(m_range);
+    CSSPrimitiveValue* keyword = consumeIdent(m_range);
     if (!keyword)
         return false;
     if (!m_range.atEnd())
@@ -4234,11 +4275,11 @@
     return true;
 }
 
-static bool consumeBackgroundPosition(CSSParserTokenRange& range, const CSSParserContext& context, UnitlessQuirk unitless, RawPtr<CSSValue>& resultX, RawPtr<CSSValue>& resultY)
+static bool consumeBackgroundPosition(CSSParserTokenRange& range, const CSSParserContext& context, UnitlessQuirk unitless, CSSValue*& resultX, CSSValue*& resultY)
 {
     do {
-        RawPtr<CSSValue> positionX = nullptr;
-        RawPtr<CSSValue> positionY = nullptr;
+        CSSValue* positionX = nullptr;
+        CSSValue* positionY = nullptr;
         if (!consumePosition(range, context.mode(), unitless, positionX, positionY))
             return false;
         addBackgroundValue(resultX, positionX);
@@ -4247,7 +4288,7 @@
     return true;
 }
 
-static bool consumeRepeatStyleComponent(CSSParserTokenRange& range, RawPtr<CSSValue>& value1, RawPtr<CSSValue>& value2, bool& implicit)
+static bool consumeRepeatStyleComponent(CSSParserTokenRange& range, CSSValue*& value1, CSSValue*& value2, bool& implicit)
 {
     if (consumeIdent<CSSValueRepeatX>(range)) {
         value1 = cssValuePool().createIdentifierValue(CSSValueRepeat);
@@ -4273,11 +4314,11 @@
     return true;
 }
 
-static bool consumeRepeatStyle(CSSParserTokenRange& range, RawPtr<CSSValue>& resultX, RawPtr<CSSValue>& resultY, bool& implicit)
+static bool consumeRepeatStyle(CSSParserTokenRange& range, CSSValue*& resultX, CSSValue*& resultY, bool& implicit)
 {
     do {
-        RawPtr<CSSValue> repeatX = nullptr;
-        RawPtr<CSSValue> repeatY = nullptr;
+        CSSValue* repeatX = nullptr;
+        CSSValue* repeatY = nullptr;
         if (!consumeRepeatStyleComponent(range, repeatX, repeatY, implicit))
             return false;
         addBackgroundValue(resultX, repeatX);
@@ -4291,7 +4332,7 @@
 bool CSSPropertyParser::consumeBackgroundShorthand(const StylePropertyShorthand& shorthand, bool important)
 {
     const unsigned longhandCount = shorthand.length();
-    RawPtr<CSSValue> longhands[10];
+    CSSValue* longhands[10];
     ASSERT(longhandCount <= 10);
 #if ENABLE(OILPAN)
     // Zero initialize the array of raw pointers.
@@ -4300,15 +4341,15 @@
     bool implicit = false;
     do {
         bool parsedLonghand[10] = { false };
-        RawPtr<CSSValue> originValue = nullptr;
+        CSSValue* originValue = nullptr;
         do {
             bool foundProperty = false;
             for (size_t i = 0; i < longhandCount; ++i) {
                 if (parsedLonghand[i])
                     continue;
 
-                RawPtr<CSSValue> value = nullptr;
-                RawPtr<CSSValue> valueY = nullptr;
+                CSSValue* value = nullptr;
+                CSSValue* valueY = nullptr;
                 CSSPropertyID property = shorthand.properties()[i];
                 if (property == CSSPropertyBackgroundRepeatX || property == CSSPropertyWebkitMaskRepeatX) {
                     consumeRepeatStyleComponent(m_range, value, valueY, implicit);
@@ -4334,10 +4375,10 @@
                         originValue = value;
                     parsedLonghand[i] = true;
                     foundProperty = true;
-                    addBackgroundValue(longhands[i], value.release());
+                    addBackgroundValue(longhands[i], value);
                     if (valueY) {
                         parsedLonghand[i + 1] = true;
-                        addBackgroundValue(longhands[i + 1], valueY.release());
+                        addBackgroundValue(longhands[i + 1], valueY);
                     }
                 }
             }
@@ -4354,7 +4395,7 @@
                 continue;
             }
             if ((property == CSSPropertyBackgroundClip || property == CSSPropertyWebkitMaskClip) && !parsedLonghand[i] && originValue) {
-                addBackgroundValue(longhands[i], originValue.release());
+                addBackgroundValue(longhands[i], originValue);
                 continue;
             }
             if (!parsedLonghand[i])
@@ -4368,7 +4409,7 @@
         CSSPropertyID property = shorthand.properties()[i];
         if (property == CSSPropertyBackgroundSize && longhands[i] && m_context.useLegacyBackgroundSizeShorthandBehavior())
             continue;
-        addProperty(property, longhands[i].release(), important, implicit);
+        addProperty(property, longhands[i], important, implicit);
     }
     return true;
 }
@@ -4378,11 +4419,11 @@
     ASSERT(RuntimeEnabledFeatures::cssGridLayoutEnabled());
     const StylePropertyShorthand& shorthand = shorthandForProperty(shorthandId);
     ASSERT(shorthand.length() == 2);
-    RawPtr<CSSValue> startValue = consumeGridLine(m_range);
+    CSSValue* startValue = consumeGridLine(m_range);
     if (!startValue)
         return false;
 
-    RawPtr<CSSValue> endValue = nullptr;
+    CSSValue* endValue = nullptr;
     if (consumeSlashIncludingWhitespace(m_range)) {
         endValue = consumeGridLine(m_range);
         if (!endValue)
@@ -4401,12 +4442,12 @@
 {
     ASSERT(RuntimeEnabledFeatures::cssGridLayoutEnabled());
     ASSERT(gridAreaShorthand().length() == 4);
-    RawPtr<CSSValue> rowStartValue = consumeGridLine(m_range);
+    CSSValue* rowStartValue = consumeGridLine(m_range);
     if (!rowStartValue)
         return false;
-    RawPtr<CSSValue> columnStartValue = nullptr;
-    RawPtr<CSSValue> rowEndValue = nullptr;
-    RawPtr<CSSValue> columnEndValue = nullptr;
+    CSSValue* columnStartValue = nullptr;
+    CSSValue* rowEndValue = nullptr;
+    CSSValue* columnEndValue = nullptr;
     if (consumeSlashIncludingWhitespace(m_range)) {
         columnStartValue = consumeGridLine(m_range);
         if (!columnStartValue)
@@ -4450,7 +4491,7 @@
         CSSValueID id = m_range.consumeIncludingWhitespace().id();
         if (!CSSParserFastPaths::isValidKeywordPropertyAndValue(CSSPropertyWebkitMarginBeforeCollapse, id))
             return false;
-        RawPtr<CSSValue> beforeCollapse = cssValuePool().createIdentifierValue(id);
+        CSSValue* beforeCollapse = cssValuePool().createIdentifierValue(id);
         addProperty(CSSPropertyWebkitMarginBeforeCollapse, beforeCollapse, important);
         if (m_range.atEnd()) {
             addProperty(CSSPropertyWebkitMarginAfterCollapse, beforeCollapse, important);
@@ -4468,9 +4509,9 @@
             return false;
         if (!m_range.atEnd())
             return false;
-        RawPtr<CSSValue> overflowYValue = cssValuePool().createIdentifierValue(id);
+        CSSValue* overflowYValue = cssValuePool().createIdentifierValue(id);
 
-        RawPtr<CSSValue> overflowXValue = nullptr;
+        CSSValue* overflowXValue = nullptr;
 
         // FIXME: -webkit-paged-x or -webkit-paged-y only apply to overflow-y. If this value has been
         // set using the shorthand, then for now overflow-x will default to auto, but once we implement
@@ -4480,8 +4521,8 @@
             overflowXValue = cssValuePool().createIdentifierValue(CSSValueAuto);
         else
             overflowXValue = overflowYValue;
-        addProperty(CSSPropertyOverflowX, overflowXValue.release(), important);
-        addProperty(CSSPropertyOverflowY, overflowYValue.release(), important);
+        addProperty(CSSPropertyOverflowX, overflowXValue, important);
+        addProperty(CSSPropertyOverflowY, overflowYValue, important);
         return true;
     }
     case CSSPropertyFont: {
@@ -4525,12 +4566,12 @@
     case CSSPropertyWebkitTextStroke:
         return consumeShorthandGreedily(webkitTextStrokeShorthand(), important);
     case CSSPropertyMarker: {
-        RawPtr<CSSValue> marker = parseSingleValue(CSSPropertyMarkerStart);
+        CSSValue* marker = parseSingleValue(CSSPropertyMarkerStart);
         if (!marker || !m_range.atEnd())
             return false;
         addProperty(CSSPropertyMarkerStart, marker, important);
         addProperty(CSSPropertyMarkerMid, marker, important);
-        addProperty(CSSPropertyMarkerEnd, marker.release(), important);
+        addProperty(CSSPropertyMarkerEnd, marker, important);
         return true;
     }
     case CSSPropertyFlex:
@@ -4542,14 +4583,14 @@
     case CSSPropertyListStyle:
         return consumeShorthandGreedily(listStyleShorthand(), important);
     case CSSPropertyBorderRadius: {
-        RawPtr<CSSPrimitiveValue> horizontalRadii[4];
-        RawPtr<CSSPrimitiveValue> verticalRadii[4];
+        CSSPrimitiveValue* horizontalRadii[4];
+        CSSPrimitiveValue* verticalRadii[4];
         if (!consumeRadii(horizontalRadii, verticalRadii, m_range, m_context.mode(), unresolvedProperty == CSSPropertyAliasWebkitBorderRadius))
             return false;
-        addProperty(CSSPropertyBorderTopLeftRadius, CSSValuePair::create(horizontalRadii[0].release(), verticalRadii[0].release(), CSSValuePair::DropIdenticalValues), important);
-        addProperty(CSSPropertyBorderTopRightRadius, CSSValuePair::create(horizontalRadii[1].release(), verticalRadii[1].release(), CSSValuePair::DropIdenticalValues), important);
-        addProperty(CSSPropertyBorderBottomRightRadius, CSSValuePair::create(horizontalRadii[2].release(), verticalRadii[2].release(), CSSValuePair::DropIdenticalValues), important);
-        addProperty(CSSPropertyBorderBottomLeftRadius, CSSValuePair::create(horizontalRadii[3].release(), verticalRadii[3].release(), CSSValuePair::DropIdenticalValues), important);
+        addProperty(CSSPropertyBorderTopLeftRadius, CSSValuePair::create(horizontalRadii[0], verticalRadii[0], CSSValuePair::DropIdenticalValues), important);
+        addProperty(CSSPropertyBorderTopRightRadius, CSSValuePair::create(horizontalRadii[1], verticalRadii[1], CSSValuePair::DropIdenticalValues), important);
+        addProperty(CSSPropertyBorderBottomRightRadius, CSSValuePair::create(horizontalRadii[2], verticalRadii[2], CSSValuePair::DropIdenticalValues), important);
+        addProperty(CSSPropertyBorderBottomLeftRadius, CSSValuePair::create(horizontalRadii[3], verticalRadii[3], CSSValuePair::DropIdenticalValues), important);
         return true;
     }
     case CSSPropertyBorderColor:
@@ -4580,23 +4621,23 @@
         return consumeLegacyBreakProperty(property, important);
     case CSSPropertyWebkitMaskPosition:
     case CSSPropertyBackgroundPosition: {
-        RawPtr<CSSValue> resultX = nullptr;
-        RawPtr<CSSValue> resultY = nullptr;
+        CSSValue* resultX = nullptr;
+        CSSValue* resultY = nullptr;
         if (!consumeBackgroundPosition(m_range, m_context, UnitlessQuirk::Allow, resultX, resultY) || !m_range.atEnd())
             return false;
-        addProperty(property == CSSPropertyBackgroundPosition ? CSSPropertyBackgroundPositionX : CSSPropertyWebkitMaskPositionX, resultX.release(), important);
-        addProperty(property == CSSPropertyBackgroundPosition ? CSSPropertyBackgroundPositionY : CSSPropertyWebkitMaskPositionY, resultY.release(), important);
+        addProperty(property == CSSPropertyBackgroundPosition ? CSSPropertyBackgroundPositionX : CSSPropertyWebkitMaskPositionX, resultX, important);
+        addProperty(property == CSSPropertyBackgroundPosition ? CSSPropertyBackgroundPositionY : CSSPropertyWebkitMaskPositionY, resultY, important);
         return true;
     }
     case CSSPropertyBackgroundRepeat:
     case CSSPropertyWebkitMaskRepeat: {
-        RawPtr<CSSValue> resultX = nullptr;
-        RawPtr<CSSValue> resultY = nullptr;
+        CSSValue* resultX = nullptr;
+        CSSValue* resultY = nullptr;
         bool implicit = false;
         if (!consumeRepeatStyle(m_range, resultX, resultY, implicit) || !m_range.atEnd())
             return false;
-        addProperty(property == CSSPropertyBackgroundRepeat ? CSSPropertyBackgroundRepeatX : CSSPropertyWebkitMaskRepeatX, resultX.release(), important, implicit);
-        addProperty(property == CSSPropertyBackgroundRepeat ? CSSPropertyBackgroundRepeatY : CSSPropertyWebkitMaskRepeatY, resultY.release(), important, implicit);
+        addProperty(property == CSSPropertyBackgroundRepeat ? CSSPropertyBackgroundRepeatX : CSSPropertyWebkitMaskRepeatX, resultX, important, implicit);
+        addProperty(property == CSSPropertyBackgroundRepeat ? CSSPropertyBackgroundRepeatY : CSSPropertyWebkitMaskRepeatY, resultY, important, implicit);
         return true;
     }
     case CSSPropertyBackground:
@@ -4605,14 +4646,14 @@
         return consumeBackgroundShorthand(webkitMaskShorthand(), important);
     case CSSPropertyGridGap: {
         ASSERT(RuntimeEnabledFeatures::cssGridLayoutEnabled() && shorthandForProperty(CSSPropertyGridGap).length() == 2);
-        RawPtr<CSSValue> rowGap = consumeLength(m_range, m_context.mode(), ValueRangeNonNegative);
-        RawPtr<CSSValue> columnGap = consumeLength(m_range, m_context.mode(), ValueRangeNonNegative);
+        CSSValue* rowGap = consumeLength(m_range, m_context.mode(), ValueRangeNonNegative);
+        CSSValue* columnGap = consumeLength(m_range, m_context.mode(), ValueRangeNonNegative);
         if (!rowGap || !m_range.atEnd())
             return false;
         if (!columnGap)
             columnGap = rowGap;
-        addProperty(CSSPropertyGridRowGap, rowGap.release(), important);
-        addProperty(CSSPropertyGridColumnGap, columnGap.release(), important);
+        addProperty(CSSPropertyGridRowGap, rowGap, important);
+        addProperty(CSSPropertyGridColumnGap, columnGap, important);
         return true;
     }
     case CSSPropertyGridColumn:
diff --git a/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.h b/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.h
index f6f5292d9..2b08146 100644
--- a/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.h
+++ b/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.h
@@ -74,7 +74,7 @@
         HeapVector<CSSProperty, 256>&, StyleRule::RuleType);
 
     // Parses a non-shorthand CSS property
-    static RawPtr<CSSValue> parseSingleValue(CSSPropertyID, const CSSParserTokenRange&, const CSSParserContext&);
+    static CSSValue* parseSingleValue(CSSPropertyID, const CSSParserTokenRange&, const CSSParserContext&);
 
     // TODO(timloh): This doesn't seem like the right place for these
     static bool isSystemColor(CSSValueID);
@@ -88,9 +88,9 @@
     // TODO(timloh): Rename once the CSSParserValue-based parseValue is removed
     bool parseValueStart(CSSPropertyID unresolvedProperty, bool important);
     bool consumeCSSWideKeyword(CSSPropertyID unresolvedProperty, bool important);
-    RawPtr<CSSValue> parseSingleValue(CSSPropertyID);
+    CSSValue* parseSingleValue(CSSPropertyID);
 
-    RawPtr<CSSValue> legacyParseValue(CSSPropertyID);
+    CSSValue* legacyParseValue(CSSPropertyID);
     bool legacyParseAndApplyValue(CSSPropertyID, bool important);
     bool legacyParseShorthand(CSSPropertyID, bool important);
 
@@ -100,8 +100,8 @@
     bool parseViewportDescriptor(CSSPropertyID propId, bool important);
     bool parseFontFaceDescriptor(CSSPropertyID);
 
-    void addProperty(CSSPropertyID, RawPtr<CSSValue>, bool important, bool implicit = false);
-    void addExpandedPropertyForValue(CSSPropertyID propId, RawPtr<CSSValue>, bool);
+    void addProperty(CSSPropertyID, CSSValue*, bool important, bool implicit = false);
+    void addExpandedPropertyForValue(CSSPropertyID propId, CSSValue*, bool);
 
     bool consumeBorder(bool important);
 
@@ -116,17 +116,17 @@
     bool consumeColumns(bool important);
 
     bool consumeGridItemPositionShorthand(CSSPropertyID, bool important);
-    RawPtr<CSSValue> parseGridTemplateColumns(bool important);
+    CSSValue* parseGridTemplateColumns(bool important);
     bool parseGridTemplateRowsAndAreasAndColumns(bool important);
     bool parseGridTemplateShorthand(bool important);
     bool parseGridShorthand(bool important);
     bool consumeGridAreaShorthand(bool important);
-    RawPtr<CSSValue> parseGridTrackList();
+    CSSValue* parseGridTrackList();
     bool parseGridTrackRepeatFunction(CSSValueList&, bool& isAutoRepeat);
-    RawPtr<CSSValue> parseGridTrackSize(CSSParserValueList& inputList, TrackSizeRestriction = AllowAll);
-    RawPtr<CSSPrimitiveValue> parseGridBreadth(CSSParserValue*, TrackSizeRestriction = AllowAll);
+    CSSValue* parseGridTrackSize(CSSParserValueList& inputList, TrackSizeRestriction = AllowAll);
+    CSSPrimitiveValue* parseGridBreadth(CSSParserValue*, TrackSizeRestriction = AllowAll);
     bool parseGridLineNames(CSSParserValueList&, CSSValueList&, CSSGridLineNamesValue* = nullptr);
-    RawPtr<CSSValue> parseGridAutoFlow(CSSParserValueList&);
+    CSSValue* parseGridAutoFlow(CSSParserValueList&);
 
     bool consumeFont(bool important);
     bool consumeSystemFont(bool important);
@@ -142,8 +142,8 @@
 
     bool parseCalculation(CSSParserValue*, ValueRange);
 
-    RawPtr<CSSPrimitiveValue> createPrimitiveNumericValue(CSSParserValue*);
-    RawPtr<CSSCustomIdentValue> createPrimitiveCustomIdentValue(CSSParserValue*);
+    CSSPrimitiveValue* createPrimitiveNumericValue(CSSParserValue*);
+    CSSCustomIdentValue* createPrimitiveCustomIdentValue(CSSParserValue*);
 
     class ShorthandScope {
         STACK_ALLOCATED();
diff --git a/third_party/WebKit/Source/core/css/parser/CSSPropertyParserHelpers.cpp b/third_party/WebKit/Source/core/css/parser/CSSPropertyParserHelpers.cpp
index bf89b1e..0fe218a 100644
--- a/third_party/WebKit/Source/core/css/parser/CSSPropertyParserHelpers.cpp
+++ b/third_party/WebKit/Source/core/css/parser/CSSPropertyParserHelpers.cpp
@@ -56,14 +56,14 @@
     }
 
     const CSSCalcValue* value() const { return m_calcValue.get(); }
-    RawPtr<CSSPrimitiveValue> consumeValue()
+    CSSPrimitiveValue* consumeValue()
     {
         if (!m_calcValue)
             return nullptr;
         m_sourceRange = m_range;
         return CSSPrimitiveValue::create(m_calcValue.release());
     }
-    RawPtr<CSSPrimitiveValue> consumeNumber()
+    CSSPrimitiveValue* consumeNumber()
     {
         if (!m_calcValue)
             return nullptr;
@@ -87,7 +87,7 @@
     Member<CSSCalcValue> m_calcValue;
 };
 
-RawPtr<CSSPrimitiveValue> consumeInteger(CSSParserTokenRange& range, double minimumValue)
+CSSPrimitiveValue* consumeInteger(CSSParserTokenRange& range, double minimumValue)
 {
     const CSSParserToken& token = range.peek();
     if (token.type() == NumberToken) {
@@ -107,7 +107,7 @@
     return nullptr;
 }
 
-RawPtr<CSSPrimitiveValue> consumePositiveInteger(CSSParserTokenRange& range)
+CSSPrimitiveValue* consumePositiveInteger(CSSParserTokenRange& range)
 {
     return consumeInteger(range, 1);
 }
@@ -123,7 +123,7 @@
 }
 
 // TODO(timloh): Work out if this can just call consumeNumberRaw
-RawPtr<CSSPrimitiveValue> consumeNumber(CSSParserTokenRange& range, ValueRange valueRange)
+CSSPrimitiveValue* consumeNumber(CSSParserTokenRange& range, ValueRange valueRange)
 {
     const CSSParserToken& token = range.peek();
     if (token.type() == NumberToken) {
@@ -150,7 +150,7 @@
         || (cssParserMode == HTMLQuirksMode && unitless == UnitlessQuirk::Allow);
 }
 
-RawPtr<CSSPrimitiveValue> consumeLength(CSSParserTokenRange& range, CSSParserMode cssParserMode, ValueRange valueRange, UnitlessQuirk unitless)
+CSSPrimitiveValue* consumeLength(CSSParserTokenRange& range, CSSParserMode cssParserMode, ValueRange valueRange, UnitlessQuirk unitless)
 {
     const CSSParserToken& token = range.peek();
     if (token.type() == DimensionToken) {
@@ -199,7 +199,7 @@
     return nullptr;
 }
 
-RawPtr<CSSPrimitiveValue> consumePercent(CSSParserTokenRange& range, ValueRange valueRange)
+CSSPrimitiveValue* consumePercent(CSSParserTokenRange& range, ValueRange valueRange)
 {
     const CSSParserToken& token = range.peek();
     if (token.type() == PercentageToken) {
@@ -215,7 +215,7 @@
     return nullptr;
 }
 
-RawPtr<CSSPrimitiveValue> consumeLengthOrPercent(CSSParserTokenRange& range, CSSParserMode cssParserMode, ValueRange valueRange, UnitlessQuirk unitless)
+CSSPrimitiveValue* consumeLengthOrPercent(CSSParserTokenRange& range, CSSParserMode cssParserMode, ValueRange valueRange, UnitlessQuirk unitless)
 {
     const CSSParserToken& token = range.peek();
     if (token.type() == DimensionToken || token.type() == NumberToken)
@@ -230,7 +230,7 @@
     return nullptr;
 }
 
-RawPtr<CSSPrimitiveValue> consumeAngle(CSSParserTokenRange& range)
+CSSPrimitiveValue* consumeAngle(CSSParserTokenRange& range)
 {
     const CSSParserToken& token = range.peek();
     if (token.type() == DimensionToken) {
@@ -256,7 +256,7 @@
     return nullptr;
 }
 
-RawPtr<CSSPrimitiveValue> consumeTime(CSSParserTokenRange& range, ValueRange valueRange)
+CSSPrimitiveValue* consumeTime(CSSParserTokenRange& range, ValueRange valueRange)
 {
     const CSSParserToken& token = range.peek();
     if (token.type() == DimensionToken) {
@@ -275,28 +275,28 @@
     return nullptr;
 }
 
-RawPtr<CSSPrimitiveValue> consumeIdent(CSSParserTokenRange& range)
+CSSPrimitiveValue* consumeIdent(CSSParserTokenRange& range)
 {
     if (range.peek().type() != IdentToken)
         return nullptr;
     return cssValuePool().createIdentifierValue(range.consumeIncludingWhitespace().id());
 }
 
-RawPtr<CSSPrimitiveValue> consumeIdentRange(CSSParserTokenRange& range, CSSValueID lower, CSSValueID upper)
+CSSPrimitiveValue* consumeIdentRange(CSSParserTokenRange& range, CSSValueID lower, CSSValueID upper)
 {
     if (range.peek().id() < lower || range.peek().id() > upper)
         return nullptr;
     return consumeIdent(range);
 }
 
-RawPtr<CSSCustomIdentValue> consumeCustomIdent(CSSParserTokenRange& range)
+CSSCustomIdentValue* consumeCustomIdent(CSSParserTokenRange& range)
 {
     if (range.peek().type() != IdentToken || isCSSWideKeyword(range.peek().id()))
         return nullptr;
     return CSSCustomIdentValue::create(range.consumeIncludingWhitespace().value());
 }
 
-RawPtr<CSSStringValue> consumeString(CSSParserTokenRange& range)
+CSSStringValue* consumeString(CSSParserTokenRange& range)
 {
     if (range.peek().type() != StringToken)
         return nullptr;
@@ -338,7 +338,7 @@
 {
     ASSERT(range.peek().functionId() == CSSValueRgb || range.peek().functionId() == CSSValueRgba);
     CSSParserTokenRange args = consumeFunction(range);
-    RawPtr<CSSPrimitiveValue> colorParameter = consumeInteger(args);
+    CSSPrimitiveValue* colorParameter = consumeInteger(args);
     if (!colorParameter)
         colorParameter = consumePercent(args, ValueRangeAll);
     if (!colorParameter)
@@ -374,7 +374,7 @@
 {
     ASSERT(range.peek().functionId() == CSSValueHsl || range.peek().functionId() == CSSValueHsla);
     CSSParserTokenRange args = consumeFunction(range);
-    RawPtr<CSSPrimitiveValue> hslValue = consumeNumber(args, ValueRangeAll);
+    CSSPrimitiveValue* hslValue = consumeNumber(args, ValueRangeAll);
     if (!hslValue)
         return false;
     double colorArray[3];
@@ -440,7 +440,7 @@
     return true;
 }
 
-RawPtr<CSSValue> consumeColor(CSSParserTokenRange& range, CSSParserMode cssParserMode, bool acceptQuirkyColors)
+CSSValue* consumeColor(CSSParserTokenRange& range, CSSParserMode cssParserMode, bool acceptQuirkyColors)
 {
     CSSValueID id = range.peek().id();
     if (CSSPropertyParser::isColorKeyword(id)) {
@@ -454,7 +454,7 @@
     return cssValuePool().createColorValue(color);
 }
 
-static RawPtr<CSSPrimitiveValue> consumePositionComponent(CSSParserTokenRange& range, CSSParserMode cssParserMode, UnitlessQuirk unitless)
+static CSSPrimitiveValue* consumePositionComponent(CSSParserTokenRange& range, CSSParserMode cssParserMode, UnitlessQuirk unitless)
 {
     if (range.peek().type() == IdentToken)
         return consumeIdent<CSSValueLeft, CSSValueTop, CSSValueBottom, CSSValueRight, CSSValueCenter>(range);
@@ -471,17 +471,17 @@
     return value.isValueID() && (value.getValueID() == CSSValueTop || value.getValueID() == CSSValueBottom);
 }
 
-static void positionFromOneValue(RawPtr<CSSPrimitiveValue> value, RawPtr<CSSValue>& resultX, RawPtr<CSSValue>& resultY)
+static void positionFromOneValue(CSSPrimitiveValue* value, CSSValue*& resultX, CSSValue*& resultY)
 {
     bool valueAppliesToYAxisOnly = isVerticalPositionKeywordOnly(*value);
     resultX = value;
     resultY = cssValuePool().createIdentifierValue(CSSValueCenter);
     if (valueAppliesToYAxisOnly)
-        swap(resultX, resultY);
+        std::swap(resultX, resultY);
 }
 
-static bool positionFromTwoValues(RawPtr<CSSPrimitiveValue> value1, RawPtr<CSSPrimitiveValue> value2,
-    RawPtr<CSSValue>& resultX, RawPtr<CSSValue>& resultY)
+static bool positionFromTwoValues(CSSPrimitiveValue* value1, CSSPrimitiveValue* value2,
+    CSSValue*& resultX, CSSValue*& resultY)
 {
     bool mustOrderAsXY = isHorizontalPositionKeywordOnly(*value1) || isVerticalPositionKeywordOnly(*value2)
         || !value1->isValueID() || !value2->isValueID();
@@ -491,11 +491,11 @@
     resultX = value1;
     resultY = value2;
     if (mustOrderAsYX)
-        swap(resultX, resultY);
+        std::swap(resultX, resultY);
     return true;
 }
 
-static bool positionFromThreeOrFourValues(CSSPrimitiveValue** values, RawPtr<CSSValue>& resultX, RawPtr<CSSValue>& resultY)
+static bool positionFromThreeOrFourValues(CSSPrimitiveValue** values, CSSValue*& resultX, CSSValue*& resultY)
 {
     CSSPrimitiveValue* center = nullptr;
     for (int i = 0; values[i]; i++) {
@@ -511,7 +511,7 @@
             continue;
         }
 
-        RawPtr<CSSValue> result = nullptr;
+        CSSValue* result = nullptr;
         if (values[i + 1] && !values[i + 1]->isValueID()) {
             result = CSSValuePair::create(currentValue, values[++i], CSSValuePair::KeepIdenticalValues);
         } else {
@@ -521,12 +521,12 @@
         if (id == CSSValueLeft || id == CSSValueRight) {
             if (resultX)
                 return false;
-            resultX = result.release();
+            resultX = result;
         } else {
             ASSERT(id == CSSValueTop || id == CSSValueBottom);
             if (resultY)
                 return false;
-            resultY = result.release();
+            resultY = result;
         }
     }
 
@@ -546,52 +546,52 @@
 
 // TODO(timloh): This may consume from the range upon failure. The background
 // shorthand works around it, but we should just fix it here.
-bool consumePosition(CSSParserTokenRange& range, CSSParserMode cssParserMode, UnitlessQuirk unitless, RawPtr<CSSValue>& resultX, RawPtr<CSSValue>& resultY)
+bool consumePosition(CSSParserTokenRange& range, CSSParserMode cssParserMode, UnitlessQuirk unitless, CSSValue*& resultX, CSSValue*& resultY)
 {
-    RawPtr<CSSPrimitiveValue> value1 = consumePositionComponent(range, cssParserMode, unitless);
+    CSSPrimitiveValue* value1 = consumePositionComponent(range, cssParserMode, unitless);
     if (!value1)
         return false;
 
-    RawPtr<CSSPrimitiveValue> value2 = consumePositionComponent(range, cssParserMode, unitless);
+    CSSPrimitiveValue* value2 = consumePositionComponent(range, cssParserMode, unitless);
     if (!value2) {
-        positionFromOneValue(value1.release(), resultX, resultY);
+        positionFromOneValue(value1, resultX, resultY);
         return true;
     }
 
-    RawPtr<CSSPrimitiveValue> value3 = consumePositionComponent(range, cssParserMode, unitless);
+    CSSPrimitiveValue* value3 = consumePositionComponent(range, cssParserMode, unitless);
     if (!value3)
-        return positionFromTwoValues(value1.release(), value2.release(), resultX, resultY);
+        return positionFromTwoValues(value1, value2, resultX, resultY);
 
-    RawPtr<CSSPrimitiveValue> value4 = consumePositionComponent(range, cssParserMode, unitless);
+    CSSPrimitiveValue* value4 = consumePositionComponent(range, cssParserMode, unitless);
     CSSPrimitiveValue* values[5];
-    values[0] = value1.get();
-    values[1] = value2.get();
-    values[2] = value3.get();
-    values[3] = value4.get();
+    values[0] = value1;
+    values[1] = value2;
+    values[2] = value3;
+    values[3] = value4;
     values[4] = nullptr;
     return positionFromThreeOrFourValues(values, resultX, resultY);
 }
 
-RawPtr<CSSValuePair> consumePosition(CSSParserTokenRange& range, CSSParserMode cssParserMode, UnitlessQuirk unitless)
+CSSValuePair* consumePosition(CSSParserTokenRange& range, CSSParserMode cssParserMode, UnitlessQuirk unitless)
 {
-    RawPtr<CSSValue> resultX = nullptr;
-    RawPtr<CSSValue> resultY = nullptr;
+    CSSValue* resultX = nullptr;
+    CSSValue* resultY = nullptr;
     if (consumePosition(range, cssParserMode, unitless, resultX, resultY))
-        return CSSValuePair::create(resultX.release(), resultY.release(), CSSValuePair::KeepIdenticalValues);
+        return CSSValuePair::create(resultX, resultY, CSSValuePair::KeepIdenticalValues);
     return nullptr;
 }
 
-bool consumeOneOrTwoValuedPosition(CSSParserTokenRange& range, CSSParserMode cssParserMode, UnitlessQuirk unitless, RawPtr<CSSValue>& resultX, RawPtr<CSSValue>& resultY)
+bool consumeOneOrTwoValuedPosition(CSSParserTokenRange& range, CSSParserMode cssParserMode, UnitlessQuirk unitless, CSSValue*& resultX, CSSValue*& resultY)
 {
-    RawPtr<CSSPrimitiveValue> value1 = consumePositionComponent(range, cssParserMode, unitless);
+    CSSPrimitiveValue* value1 = consumePositionComponent(range, cssParserMode, unitless);
     if (!value1)
         return false;
-    RawPtr<CSSPrimitiveValue> value2 = consumePositionComponent(range, cssParserMode, unitless);
+    CSSPrimitiveValue* value2 = consumePositionComponent(range, cssParserMode, unitless);
     if (!value2) {
-        positionFromOneValue(value1.release(), resultX, resultY);
+        positionFromOneValue(value1, resultX, resultY);
         return true;
     }
-    return positionFromTwoValues(value1.release(), value2.release(), resultX, resultY);
+    return positionFromTwoValues(value1, value2, resultX, resultY);
 }
 
 } // namespace CSSPropertyParserHelpers
diff --git a/third_party/WebKit/Source/core/css/parser/CSSPropertyParserHelpers.h b/third_party/WebKit/Source/core/css/parser/CSSPropertyParserHelpers.h
index 9a9e9b51..314ad5f 100644
--- a/third_party/WebKit/Source/core/css/parser/CSSPropertyParserHelpers.h
+++ b/third_party/WebKit/Source/core/css/parser/CSSPropertyParserHelpers.h
@@ -33,30 +33,30 @@
     Forbid
 };
 
-RawPtr<CSSPrimitiveValue> consumeInteger(CSSParserTokenRange&, double minimumValue = -std::numeric_limits<double>::max());
-RawPtr<CSSPrimitiveValue> consumePositiveInteger(CSSParserTokenRange&);
+CSSPrimitiveValue* consumeInteger(CSSParserTokenRange&, double minimumValue = -std::numeric_limits<double>::max());
+CSSPrimitiveValue* consumePositiveInteger(CSSParserTokenRange&);
 bool consumeNumberRaw(CSSParserTokenRange&, double& result);
-RawPtr<CSSPrimitiveValue> consumeNumber(CSSParserTokenRange&, ValueRange);
-RawPtr<CSSPrimitiveValue> consumeLength(CSSParserTokenRange&, CSSParserMode, ValueRange, UnitlessQuirk = UnitlessQuirk::Forbid);
-RawPtr<CSSPrimitiveValue> consumePercent(CSSParserTokenRange&, ValueRange);
-RawPtr<CSSPrimitiveValue> consumeLengthOrPercent(CSSParserTokenRange&, CSSParserMode, ValueRange, UnitlessQuirk = UnitlessQuirk::Forbid);
-RawPtr<CSSPrimitiveValue> consumeAngle(CSSParserTokenRange&);
-RawPtr<CSSPrimitiveValue> consumeTime(CSSParserTokenRange&, ValueRange);
+CSSPrimitiveValue* consumeNumber(CSSParserTokenRange&, ValueRange);
+CSSPrimitiveValue* consumeLength(CSSParserTokenRange&, CSSParserMode, ValueRange, UnitlessQuirk = UnitlessQuirk::Forbid);
+CSSPrimitiveValue* consumePercent(CSSParserTokenRange&, ValueRange);
+CSSPrimitiveValue* consumeLengthOrPercent(CSSParserTokenRange&, CSSParserMode, ValueRange, UnitlessQuirk = UnitlessQuirk::Forbid);
+CSSPrimitiveValue* consumeAngle(CSSParserTokenRange&);
+CSSPrimitiveValue* consumeTime(CSSParserTokenRange&, ValueRange);
 
-RawPtr<CSSPrimitiveValue> consumeIdent(CSSParserTokenRange&);
-RawPtr<CSSPrimitiveValue> consumeIdentRange(CSSParserTokenRange&, CSSValueID lower, CSSValueID upper);
+CSSPrimitiveValue* consumeIdent(CSSParserTokenRange&);
+CSSPrimitiveValue* consumeIdentRange(CSSParserTokenRange&, CSSValueID lower, CSSValueID upper);
 template<CSSValueID, CSSValueID...> inline bool identMatches(CSSValueID id);
-template<CSSValueID... allowedIdents> RawPtr<CSSPrimitiveValue> consumeIdent(CSSParserTokenRange&);
+template<CSSValueID... allowedIdents> CSSPrimitiveValue* consumeIdent(CSSParserTokenRange&);
 
-RawPtr<CSSCustomIdentValue> consumeCustomIdent(CSSParserTokenRange&);
-RawPtr<CSSStringValue> consumeString(CSSParserTokenRange&);
+CSSCustomIdentValue* consumeCustomIdent(CSSParserTokenRange&);
+CSSStringValue* consumeString(CSSParserTokenRange&);
 String consumeUrl(CSSParserTokenRange&);
 
-RawPtr<CSSValue> consumeColor(CSSParserTokenRange&, CSSParserMode, bool acceptQuirkyColors = false);
+CSSValue* consumeColor(CSSParserTokenRange&, CSSParserMode, bool acceptQuirkyColors = false);
 
-RawPtr<CSSValuePair> consumePosition(CSSParserTokenRange&, CSSParserMode, UnitlessQuirk);
-bool consumePosition(CSSParserTokenRange&, CSSParserMode, UnitlessQuirk, RawPtr<CSSValue>& resultX, RawPtr<CSSValue>& resultY);
-bool consumeOneOrTwoValuedPosition(CSSParserTokenRange&, CSSParserMode, UnitlessQuirk, RawPtr<CSSValue>& resultX, RawPtr<CSSValue>& resultY);
+CSSValuePair* consumePosition(CSSParserTokenRange&, CSSParserMode, UnitlessQuirk);
+bool consumePosition(CSSParserTokenRange&, CSSParserMode, UnitlessQuirk, CSSValue*& resultX, CSSValue*& resultY);
+bool consumeOneOrTwoValuedPosition(CSSParserTokenRange&, CSSParserMode, UnitlessQuirk, CSSValue*& resultX, CSSValue*& resultY);
 
 // TODO(timloh): Move across consumeImage
 
@@ -68,7 +68,7 @@
     return id == head || identMatches<tail...>(id);
 }
 
-template<CSSValueID... names> RawPtr<CSSPrimitiveValue> consumeIdent(CSSParserTokenRange& range)
+template<CSSValueID... names> CSSPrimitiveValue* consumeIdent(CSSParserTokenRange& range)
 {
     if (range.peek().type() != IdentToken || !identMatches<names...>(range.peek().id()))
         return nullptr;
diff --git a/third_party/WebKit/Source/core/css/parser/CSSPropertyParserTest.cpp b/third_party/WebKit/Source/core/css/parser/CSSPropertyParserTest.cpp
index 5d56cc7..618c5bb 100644
--- a/third_party/WebKit/Source/core/css/parser/CSSPropertyParserTest.cpp
+++ b/third_party/WebKit/Source/core/css/parser/CSSPropertyParserTest.cpp
@@ -23,130 +23,130 @@
 
 TEST(CSSPropertyParserTest, GridTrackLimit1)
 {
-    RawPtr<CSSValue> value = CSSParser::parseSingleValue(CSSPropertyGridTemplateColumns, "repeat(999999, 20px)");
+    CSSValue* value = CSSParser::parseSingleValue(CSSPropertyGridTemplateColumns, "repeat(999999, 20px)");
     ASSERT_TRUE(value);
     ASSERT_TRUE(value->isValueList());
-    EXPECT_EQ(computeNumberOfTracks(toCSSValueList(value.get())), 999999);
+    EXPECT_EQ(computeNumberOfTracks(toCSSValueList(value)), 999999);
 }
 
 TEST(CSSPropertyParserTest, GridTrackLimit2)
 {
-    RawPtr<CSSValue> value = CSSParser::parseSingleValue(CSSPropertyGridTemplateRows, "repeat(999999, 20px)");
+    CSSValue* value = CSSParser::parseSingleValue(CSSPropertyGridTemplateRows, "repeat(999999, 20px)");
     ASSERT_TRUE(value);
     ASSERT_TRUE(value->isValueList());
-    EXPECT_EQ(computeNumberOfTracks(toCSSValueList(value.get())), 999999);
+    EXPECT_EQ(computeNumberOfTracks(toCSSValueList(value)), 999999);
 }
 
 TEST(CSSPropertyParserTest, GridTrackLimit3)
 {
-    RawPtr<CSSValue> value = CSSParser::parseSingleValue(CSSPropertyGridTemplateColumns, "repeat(1000000, 10%)");
+    CSSValue* value = CSSParser::parseSingleValue(CSSPropertyGridTemplateColumns, "repeat(1000000, 10%)");
     ASSERT_TRUE(value);
     ASSERT_TRUE(value->isValueList());
-    EXPECT_EQ(computeNumberOfTracks(toCSSValueList(value.get())), 1000000);
+    EXPECT_EQ(computeNumberOfTracks(toCSSValueList(value)), 1000000);
 }
 
 TEST(CSSPropertyParserTest, GridTrackLimit4)
 {
-    RawPtr<CSSValue> value = CSSParser::parseSingleValue(CSSPropertyGridTemplateRows, "repeat(1000000, 10%)");
+    CSSValue* value = CSSParser::parseSingleValue(CSSPropertyGridTemplateRows, "repeat(1000000, 10%)");
     ASSERT_TRUE(value);
     ASSERT_TRUE(value->isValueList());
-    EXPECT_EQ(computeNumberOfTracks(toCSSValueList(value.get())), 1000000);
+    EXPECT_EQ(computeNumberOfTracks(toCSSValueList(value)), 1000000);
 }
 
 TEST(CSSPropertyParserTest, GridTrackLimit5)
 {
-    RawPtr<CSSValue> value = CSSParser::parseSingleValue(CSSPropertyGridTemplateColumns, "repeat(1000000, [first] min-content [last])");
+    CSSValue* value = CSSParser::parseSingleValue(CSSPropertyGridTemplateColumns, "repeat(1000000, [first] min-content [last])");
     ASSERT_TRUE(value);
     ASSERT_TRUE(value->isValueList());
-    EXPECT_EQ(computeNumberOfTracks(toCSSValueList(value.get())), 1000000);
+    EXPECT_EQ(computeNumberOfTracks(toCSSValueList(value)), 1000000);
 }
 
 TEST(CSSPropertyParserTest, GridTrackLimit6)
 {
-    RawPtr<CSSValue> value = CSSParser::parseSingleValue(CSSPropertyGridTemplateRows, "repeat(1000000, [first] min-content [last])");
+    CSSValue* value = CSSParser::parseSingleValue(CSSPropertyGridTemplateRows, "repeat(1000000, [first] min-content [last])");
     ASSERT_TRUE(value);
     ASSERT_TRUE(value->isValueList());
-    EXPECT_EQ(computeNumberOfTracks(toCSSValueList(value.get())), 1000000);
+    EXPECT_EQ(computeNumberOfTracks(toCSSValueList(value)), 1000000);
 }
 
 TEST(CSSPropertyParserTest, GridTrackLimit7)
 {
-    RawPtr<CSSValue> value = CSSParser::parseSingleValue(CSSPropertyGridTemplateColumns, "repeat(1000001, auto)");
+    CSSValue* value = CSSParser::parseSingleValue(CSSPropertyGridTemplateColumns, "repeat(1000001, auto)");
     ASSERT_TRUE(value);
     ASSERT_TRUE(value->isValueList());
-    EXPECT_EQ(computeNumberOfTracks(toCSSValueList(value.get())), 1000000);
+    EXPECT_EQ(computeNumberOfTracks(toCSSValueList(value)), 1000000);
 }
 
 TEST(CSSPropertyParserTest, GridTrackLimit8)
 {
-    RawPtr<CSSValue> value = CSSParser::parseSingleValue(CSSPropertyGridTemplateRows, "repeat(1000001, auto)");
+    CSSValue* value = CSSParser::parseSingleValue(CSSPropertyGridTemplateRows, "repeat(1000001, auto)");
     ASSERT_TRUE(value);
     ASSERT_TRUE(value->isValueList());
-    EXPECT_EQ(computeNumberOfTracks(toCSSValueList(value.get())), 1000000);
+    EXPECT_EQ(computeNumberOfTracks(toCSSValueList(value)), 1000000);
 }
 
 TEST(CSSPropertyParserTest, GridTrackLimit9)
 {
-    RawPtr<CSSValue> value = CSSParser::parseSingleValue(CSSPropertyGridTemplateColumns, "repeat(400000, 2em minmax(10px, max-content) 0.5fr)");
+    CSSValue* value = CSSParser::parseSingleValue(CSSPropertyGridTemplateColumns, "repeat(400000, 2em minmax(10px, max-content) 0.5fr)");
     ASSERT_TRUE(value);
     ASSERT_TRUE(value->isValueList());
-    EXPECT_EQ(computeNumberOfTracks(toCSSValueList(value.get())), 999999);
+    EXPECT_EQ(computeNumberOfTracks(toCSSValueList(value)), 999999);
 }
 
 TEST(CSSPropertyParserTest, GridTrackLimit10)
 {
-    RawPtr<CSSValue> value = CSSParser::parseSingleValue(CSSPropertyGridTemplateRows, "repeat(400000, 2em minmax(10px, max-content) 0.5fr)");
+    CSSValue* value = CSSParser::parseSingleValue(CSSPropertyGridTemplateRows, "repeat(400000, 2em minmax(10px, max-content) 0.5fr)");
     ASSERT_TRUE(value);
     ASSERT_TRUE(value->isValueList());
-    EXPECT_EQ(computeNumberOfTracks(toCSSValueList(value.get())), 999999);
+    EXPECT_EQ(computeNumberOfTracks(toCSSValueList(value)), 999999);
 }
 
 TEST(CSSPropertyParserTest, GridTrackLimit11)
 {
-    RawPtr<CSSValue> value = CSSParser::parseSingleValue(CSSPropertyGridTemplateColumns, "repeat(600000, [first] 3vh 10% 2fr [nav] 10px auto 1fr 6em [last])");
+    CSSValue* value = CSSParser::parseSingleValue(CSSPropertyGridTemplateColumns, "repeat(600000, [first] 3vh 10% 2fr [nav] 10px auto 1fr 6em [last])");
     ASSERT_TRUE(value);
     ASSERT_TRUE(value->isValueList());
-    EXPECT_EQ(computeNumberOfTracks(toCSSValueList(value.get())), 999999);
+    EXPECT_EQ(computeNumberOfTracks(toCSSValueList(value)), 999999);
 }
 
 TEST(CSSPropertyParserTest, GridTrackLimit12)
 {
-    RawPtr<CSSValue> value = CSSParser::parseSingleValue(CSSPropertyGridTemplateRows, "repeat(600000, [first] 3vh 10% 2fr [nav] 10px auto 1fr 6em [last])");
+    CSSValue* value = CSSParser::parseSingleValue(CSSPropertyGridTemplateRows, "repeat(600000, [first] 3vh 10% 2fr [nav] 10px auto 1fr 6em [last])");
     ASSERT_TRUE(value);
     ASSERT_TRUE(value->isValueList());
-    EXPECT_EQ(computeNumberOfTracks(toCSSValueList(value.get())), 999999);
+    EXPECT_EQ(computeNumberOfTracks(toCSSValueList(value)), 999999);
 }
 
 TEST(CSSPropertyParserTest, GridTrackLimit13)
 {
-    RawPtr<CSSValue> value = CSSParser::parseSingleValue(CSSPropertyGridTemplateColumns, "repeat(100000000000000000000, 10% 1fr)");
+    CSSValue* value = CSSParser::parseSingleValue(CSSPropertyGridTemplateColumns, "repeat(100000000000000000000, 10% 1fr)");
     ASSERT_TRUE(value);
     ASSERT_TRUE(value->isValueList());
-    EXPECT_EQ(computeNumberOfTracks(toCSSValueList(value.get())), 1000000);
+    EXPECT_EQ(computeNumberOfTracks(toCSSValueList(value)), 1000000);
 }
 
 TEST(CSSPropertyParserTest, GridTrackLimit14)
 {
-    RawPtr<CSSValue> value = CSSParser::parseSingleValue(CSSPropertyGridTemplateRows, "repeat(100000000000000000000, 10% 1fr)");
+    CSSValue* value = CSSParser::parseSingleValue(CSSPropertyGridTemplateRows, "repeat(100000000000000000000, 10% 1fr)");
     ASSERT_TRUE(value);
     ASSERT_TRUE(value->isValueList());
-    EXPECT_EQ(computeNumberOfTracks(toCSSValueList(value.get())), 1000000);
+    EXPECT_EQ(computeNumberOfTracks(toCSSValueList(value)), 1000000);
 }
 
 TEST(CSSPropertyParserTest, GridTrackLimit15)
 {
-    RawPtr<CSSValue> value = CSSParser::parseSingleValue(CSSPropertyGridTemplateColumns, "repeat(100000000000000000000, 10% 5em 1fr auto auto 15px min-content)");
+    CSSValue* value = CSSParser::parseSingleValue(CSSPropertyGridTemplateColumns, "repeat(100000000000000000000, 10% 5em 1fr auto auto 15px min-content)");
     ASSERT_TRUE(value);
     ASSERT_TRUE(value->isValueList());
-    EXPECT_EQ(computeNumberOfTracks(toCSSValueList(value.get())), 999999);
+    EXPECT_EQ(computeNumberOfTracks(toCSSValueList(value)), 999999);
 }
 
 TEST(CSSPropertyParserTest, GridTrackLimit16)
 {
-    RawPtr<CSSValue> value = CSSParser::parseSingleValue(CSSPropertyGridTemplateRows, "repeat(100000000000000000000, 10% 5em 1fr auto auto 15px min-content)");
+    CSSValue* value = CSSParser::parseSingleValue(CSSPropertyGridTemplateRows, "repeat(100000000000000000000, 10% 5em 1fr auto auto 15px min-content)");
     ASSERT_TRUE(value);
     ASSERT_TRUE(value->isValueList());
-    EXPECT_EQ(computeNumberOfTracks(toCSSValueList(value.get())), 999999);
+    EXPECT_EQ(computeNumberOfTracks(toCSSValueList(value)), 999999);
 }
 
 } // namespace blink
diff --git a/third_party/WebKit/Source/core/css/parser/CSSSelectorParserTest.cpp b/third_party/WebKit/Source/core/css/parser/CSSSelectorParserTest.cpp
index ab5006d..08abeef 100644
--- a/third_party/WebKit/Source/core/css/parser/CSSSelectorParserTest.cpp
+++ b/third_party/WebKit/Source/core/css/parser/CSSSelectorParserTest.cpp
@@ -262,12 +262,12 @@
     };
 
     CSSParserContext context(HTMLStandardMode, nullptr);
-    RawPtr<StyleSheetContents> sheet = StyleSheetContents::create(context);
+    StyleSheetContents* sheet = StyleSheetContents::create(context);
 
     for (auto testCase : testCases) {
         CSSTokenizer::Scope scope(testCase);
         CSSParserTokenRange range = scope.tokenRange();
-        CSSSelectorList list = CSSSelectorParser::parseSelector(range, context, sheet.get());
+        CSSSelectorList list = CSSSelectorParser::parseSelector(range, context, sheet);
         EXPECT_FALSE(list.isValid());
     }
 }
@@ -292,14 +292,14 @@
     };
 
     CSSParserContext context(HTMLStandardMode, nullptr);
-    RawPtr<StyleSheetContents> sheet = StyleSheetContents::create(context);
+    StyleSheetContents* sheet = StyleSheetContents::create(context);
     sheet->parserAddNamespace("ns", "http://ns.org");
 
     for (auto testCase : testCases) {
         SCOPED_TRACE(testCase[0]);
         CSSTokenizer::Scope scope(testCase[0]);
         CSSParserTokenRange range = scope.tokenRange();
-        CSSSelectorList list = CSSSelectorParser::parseSelector(range, context, sheet.get());
+        CSSSelectorList list = CSSSelectorParser::parseSelector(range, context, sheet);
         EXPECT_TRUE(list.isValid());
         EXPECT_STREQ(testCase[1], list.selectorsText().ascii().data());
     }
diff --git a/third_party/WebKit/Source/core/css/parser/CSSVariableParser.cpp b/third_party/WebKit/Source/core/css/parser/CSSVariableParser.cpp
index f1a7e0d..86c7d731 100644
--- a/third_party/WebKit/Source/core/css/parser/CSSVariableParser.cpp
+++ b/third_party/WebKit/Source/core/css/parser/CSSVariableParser.cpp
@@ -122,7 +122,7 @@
     return type == CSSValueInternalVariableValue && hasReferences && !hasAtApplyRule;
 }
 
-RawPtr<CSSCustomPropertyDeclaration> CSSVariableParser::parseDeclarationValue(const AtomicString& variableName, CSSParserTokenRange range)
+CSSCustomPropertyDeclaration* CSSVariableParser::parseDeclarationValue(const AtomicString& variableName, CSSParserTokenRange range)
 {
     if (range.atEnd())
         return nullptr;
diff --git a/third_party/WebKit/Source/core/css/parser/CSSVariableParser.h b/third_party/WebKit/Source/core/css/parser/CSSVariableParser.h
index dbda30f..dadf926c 100644
--- a/third_party/WebKit/Source/core/css/parser/CSSVariableParser.h
+++ b/third_party/WebKit/Source/core/css/parser/CSSVariableParser.h
@@ -18,7 +18,7 @@
 public:
     static bool containsValidVariableReferences(CSSParserTokenRange);
 
-    static RawPtr<CSSCustomPropertyDeclaration> parseDeclarationValue(const AtomicString&, CSSParserTokenRange);
+    static CSSCustomPropertyDeclaration* parseDeclarationValue(const AtomicString&, CSSParserTokenRange);
 
     static bool isValidVariableName(const CSSParserToken&);
     static bool isValidVariableName(const String&);
diff --git a/third_party/WebKit/Source/core/css/parser/LegacyCSSPropertyParser.cpp b/third_party/WebKit/Source/core/css/parser/LegacyCSSPropertyParser.cpp
index e077752..62a4849 100644
--- a/third_party/WebKit/Source/core/css/parser/LegacyCSSPropertyParser.cpp
+++ b/third_party/WebKit/Source/core/css/parser/LegacyCSSPropertyParser.cpp
@@ -40,7 +40,7 @@
 
 namespace blink {
 
-void CSSPropertyParser::addProperty(CSSPropertyID propId, RawPtr<CSSValue> value, bool important, bool implicit)
+void CSSPropertyParser::addProperty(CSSPropertyID propId, CSSValue* value, bool important, bool implicit)
 {
     ASSERT(!isPropertyAlias(propId));
 
@@ -192,7 +192,7 @@
     }
 }
 
-RawPtr<CSSPrimitiveValue> CSSPropertyParser::createPrimitiveNumericValue(CSSParserValue* value)
+CSSPrimitiveValue* CSSPropertyParser::createPrimitiveNumericValue(CSSParserValue* value)
 {
     if (m_parsedCalculation) {
         ASSERT(isCalculation(value));
@@ -206,7 +206,7 @@
     return cssValuePool().createValue(value->fValue, value->unit());
 }
 
-inline RawPtr<CSSCustomIdentValue> CSSPropertyParser::createPrimitiveCustomIdentValue(CSSParserValue* value)
+inline CSSCustomIdentValue* CSSPropertyParser::createPrimitiveCustomIdentValue(CSSParserValue* value)
 {
     ASSERT(value->m_unit == CSSParserValue::String || value->m_unit == CSSParserValue::Identifier);
     return CSSCustomIdentValue::create(value->string);
@@ -224,16 +224,15 @@
     return value->m_unit == CSSParserValue::Operator && value->iValue == '/';
 }
 
-void CSSPropertyParser::addExpandedPropertyForValue(CSSPropertyID propId, RawPtr<CSSValue> prpValue, bool important)
+void CSSPropertyParser::addExpandedPropertyForValue(CSSPropertyID propId, CSSValue* value, bool important)
 {
     const StylePropertyShorthand& shorthand = shorthandForProperty(propId);
     unsigned shorthandLength = shorthand.length();
     if (!shorthandLength) {
-        addProperty(propId, prpValue, important);
+        addProperty(propId, value, important);
         return;
     }
 
-    RawPtr<CSSValue> value = prpValue;
     ShorthandScope scope(this, propId);
     const CSSPropertyID* longhands = shorthand.properties();
     for (unsigned i = 0; i < shorthandLength; ++i)
@@ -242,14 +241,14 @@
 
 bool CSSPropertyParser::legacyParseAndApplyValue(CSSPropertyID propertyID, bool important)
 {
-    RawPtr<CSSValue> result = legacyParseValue(propertyID);
+    CSSValue* result = legacyParseValue(propertyID);
     if (!result)
         return false;
-    addProperty(propertyID, result.release(), important);
+    addProperty(propertyID, result, important);
     return true;
 }
 
-RawPtr<CSSValue> CSSPropertyParser::legacyParseValue(CSSPropertyID unresolvedProperty)
+CSSValue* CSSPropertyParser::legacyParseValue(CSSPropertyID unresolvedProperty)
 {
     CSSPropertyID propId = resolveCSSPropertyID(unresolvedProperty);
 
@@ -257,7 +256,7 @@
     // FIXME: This is to avoid having to pass parsedCalc to all validUnit callers.
     ASSERT(!m_parsedCalculation);
 
-    RawPtr<CSSValue> parsedValue = nullptr;
+    CSSValue* parsedValue = nullptr;
 
     switch (propId) {
     case CSSPropertyGridAutoFlow:
@@ -273,7 +272,7 @@
     ASSERT(!m_parsedCalculation);
     if (parsedValue) {
         if (!m_valueList->current() || inShorthand())
-            return parsedValue.release();
+            return parsedValue;
     }
     return nullptr;
 }
@@ -306,11 +305,11 @@
     return value.m_unit == CSSParserValue::Identifier && value.id != CSSValueSpan && value.id != CSSValueAuto && !isCSSWideKeyword(value);
 }
 
-RawPtr<CSSValue> CSSPropertyParser::parseGridTemplateColumns(bool important)
+CSSValue* CSSPropertyParser::parseGridTemplateColumns(bool important)
 {
     if (!(m_valueList->current() && isForwardSlashOperator(m_valueList->current()) && m_valueList->next()))
         return nullptr;
-    if (RawPtr<CSSValue> columnsValue = parseGridTrackList()) {
+    if (CSSValue* columnsValue = parseGridTrackList()) {
         if (m_valueList->current())
             return nullptr;
         return columnsValue;
@@ -325,7 +324,7 @@
     size_t rowCount = 0;
     size_t columnCount = 0;
     bool trailingIdentWasAdded = false;
-    RawPtr<CSSValueList> templateRows = CSSValueList::createSpaceSeparated();
+    CSSValueList* templateRows = CSSValueList::createSpaceSeparated();
 
     // At least template-areas strings must be defined.
     if (!m_valueList->current() || isForwardSlashOperator(m_valueList->current()))
@@ -347,7 +346,7 @@
 
         // Handle template-rows's track-size.
         if (m_valueList->current() && m_valueList->current()->m_unit != CSSParserValue::Operator && m_valueList->current()->m_unit != CSSParserValue::String) {
-            RawPtr<CSSValue> value = parseGridTrackSize(*m_valueList);
+            CSSValue* value = parseGridTrackSize(*m_valueList);
             if (!value)
                 return false;
             templateRows->append(value);
@@ -361,7 +360,7 @@
         trailingIdentWasAdded = templateRows->item(templateRows->length() - 1)->isGridLineNamesValue();
     }
 
-    RawPtr<CSSValue> columnsValue = nullptr;
+    CSSValue* columnsValue = nullptr;
     if (m_valueList->current()) {
         ASSERT(isForwardSlashOperator(m_valueList->current()));
         columnsValue = parseGridTemplateColumns(important);
@@ -372,11 +371,11 @@
             return false;
     }
 
-    addProperty(CSSPropertyGridTemplateRows, templateRows.release(), important);
-    addProperty(CSSPropertyGridTemplateColumns, columnsValue ? columnsValue.release() : cssValuePool().createIdentifierValue(CSSValueNone), important);
+    addProperty(CSSPropertyGridTemplateRows, templateRows, important);
+    addProperty(CSSPropertyGridTemplateColumns, columnsValue ? columnsValue : cssValuePool().createIdentifierValue(CSSValueNone), important);
 
-    RawPtr<CSSValue> templateAreas = CSSGridTemplateAreasValue::create(gridAreaMap, rowCount, columnCount);
-    addProperty(CSSPropertyGridTemplateAreas, templateAreas.release(), important);
+    CSSValue* templateAreas = CSSGridTemplateAreasValue::create(gridAreaMap, rowCount, columnCount);
+    addProperty(CSSPropertyGridTemplateAreas, templateAreas, important);
 
     return true;
 }
@@ -404,7 +403,7 @@
     }
 
     // 2- <grid-template-rows> / <grid-template-columns>
-    RawPtr<CSSValue> rowsValue = nullptr;
+    CSSValue* rowsValue = nullptr;
     if (firstValueIsNone) {
         rowsValue = cssValuePool().createIdentifierValue(CSSValueNone);
     } else {
@@ -412,12 +411,12 @@
     }
 
     if (rowsValue) {
-        RawPtr<CSSValue> columnsValue = parseGridTemplateColumns(important);
+        CSSValue* columnsValue = parseGridTemplateColumns(important);
         if (!columnsValue)
             return false;
 
-        addProperty(CSSPropertyGridTemplateRows, rowsValue.release(), important);
-        addProperty(CSSPropertyGridTemplateColumns, columnsValue.release(), important);
+        addProperty(CSSPropertyGridTemplateRows, rowsValue, important);
+        addProperty(CSSPropertyGridTemplateColumns, columnsValue, important);
         addProperty(CSSPropertyGridTemplateAreas, cssValuePool().createIdentifierValue(CSSValueNone), important);
         return true;
     }
@@ -452,8 +451,8 @@
     if (!legacyParseAndApplyValue(CSSPropertyGridAutoFlow, important))
         return false;
 
-    RawPtr<CSSValue> autoColumnsValue = nullptr;
-    RawPtr<CSSValue> autoRowsValue = nullptr;
+    CSSValue* autoColumnsValue = nullptr;
+    CSSValue* autoRowsValue = nullptr;
 
     if (m_valueList->current()) {
         autoRowsValue = parseGridTrackSize(*m_valueList);
@@ -505,7 +504,7 @@
     // Skip '['
     inputList.next();
 
-    RawPtr<CSSGridLineNamesValue> lineNames = previousNamedAreaTrailingLineNames;
+    CSSGridLineNamesValue* lineNames = previousNamedAreaTrailingLineNames;
     if (!lineNames)
         lineNames = CSSGridLineNamesValue::create();
 
@@ -516,8 +515,8 @@
         if (!isValidCustomIdentForGridPositions(*identValue))
             return false;
 
-        RawPtr<CSSCustomIdentValue> lineName = createPrimitiveCustomIdentValue(identValue);
-        lineNames->append(lineName.release());
+        CSSCustomIdentValue* lineName = createPrimitiveCustomIdentValue(identValue);
+        lineNames->append(lineName);
         inputList.next();
     }
 
@@ -525,7 +524,7 @@
         return false;
 
     if (!previousNamedAreaTrailingLineNames)
-        valueList.append(lineNames.release());
+        valueList.append(lineNames);
 
     // Consume ']'
     inputList.next();
@@ -554,7 +553,7 @@
     return true;
 }
 
-RawPtr<CSSValue> CSSPropertyParser::parseGridTrackList()
+CSSValue* CSSPropertyParser::parseGridTrackList()
 {
     ASSERT(RuntimeEnabledFeatures::cssGridLayoutEnabled());
 
@@ -564,7 +563,7 @@
         return cssValuePool().createIdentifierValue(CSSValueNone);
     }
 
-    RawPtr<CSSValueList> values = CSSValueList::createSpaceSeparated();
+    CSSValueList* values = CSSValueList::createSpaceSeparated();
     // Handle leading  <custom-ident>*.
     if (!parseGridLineNames(*m_valueList, *values))
         return nullptr;
@@ -583,7 +582,7 @@
             seenTrackSizeOrRepeatFunction = true;
             seenAutoRepeat = seenAutoRepeat || isAutoRepeat;
         } else {
-            RawPtr<CSSValue> value = parseGridTrackSize(*m_valueList, seenAutoRepeat ? FixedSizeOnly : AllowAll);
+            CSSValue* value = parseGridTrackSize(*m_valueList, seenAutoRepeat ? FixedSizeOnly : AllowAll);
             if (!value)
                 return nullptr;
             values->append(value);
@@ -621,7 +620,7 @@
     // because it will be computed later, let's set it to 1.
     size_t repetitions = isAutoRepeat ? 1 : clampTo<size_t>(currentValue->fValue, 0, kGridMaxTracks);
 
-    RawPtr<CSSValueList> repeatedValues = isAutoRepeat ? CSSGridAutoRepeatValue::create(currentValue->id) : CSSValueList::createSpaceSeparated();
+    CSSValueList* repeatedValues = isAutoRepeat ? CSSGridAutoRepeatValue::create(currentValue->id) : CSSValueList::createSpaceSeparated();
     arguments->next(); // Skip the repetition count.
     arguments->next(); // Skip the comma.
 
@@ -635,7 +634,7 @@
         if (isAutoRepeat && numberOfTracks)
             return false;
 
-        RawPtr<CSSValue> trackSize = parseGridTrackSize(*arguments, restriction);
+        CSSValue* trackSize = parseGridTrackSize(*arguments, restriction);
         if (!trackSize)
             return false;
 
@@ -652,7 +651,7 @@
         return false;
 
     if (isAutoRepeat) {
-        list.append(repeatedValues.release());
+        list.append(repeatedValues);
     } else {
         // We clamp the number of repetitions to a multiple of the repeat() track list's size, while staying below the max
         // grid size.
@@ -670,7 +669,7 @@
 }
 
 
-RawPtr<CSSValue> CSSPropertyParser::parseGridTrackSize(CSSParserValueList& inputList, TrackSizeRestriction restriction)
+CSSValue* CSSPropertyParser::parseGridTrackSize(CSSParserValueList& inputList, TrackSizeRestriction restriction)
 {
     ASSERT(RuntimeEnabledFeatures::cssGridLayoutEnabled());
 
@@ -686,24 +685,24 @@
         if (!arguments || arguments->size() != 3 || !isComma(arguments->valueAt(1)))
             return nullptr;
 
-        RawPtr<CSSPrimitiveValue> minTrackBreadth = parseGridBreadth(arguments->valueAt(0), restriction);
+        CSSPrimitiveValue* minTrackBreadth = parseGridBreadth(arguments->valueAt(0), restriction);
         if (!minTrackBreadth)
             return nullptr;
 
-        RawPtr<CSSPrimitiveValue> maxTrackBreadth = parseGridBreadth(arguments->valueAt(2));
+        CSSPrimitiveValue* maxTrackBreadth = parseGridBreadth(arguments->valueAt(2));
         if (!maxTrackBreadth)
             return nullptr;
 
-        RawPtr<CSSFunctionValue> result = CSSFunctionValue::create(CSSValueMinmax);
+        CSSFunctionValue* result = CSSFunctionValue::create(CSSValueMinmax);
         result->append(minTrackBreadth);
         result->append(maxTrackBreadth);
-        return result.release();
+        return result;
     }
 
     return parseGridBreadth(currentValue, restriction);
 }
 
-RawPtr<CSSPrimitiveValue> CSSPropertyParser::parseGridBreadth(CSSParserValue* currentValue, TrackSizeRestriction restriction)
+CSSPrimitiveValue* CSSPropertyParser::parseGridBreadth(CSSParserValue* currentValue, TrackSizeRestriction restriction)
 {
     if (currentValue->id == CSSValueMinContent || currentValue->id == CSSValueMaxContent || currentValue->id == CSSValueAuto)
         return restriction == AllowAll ? cssValuePool().createIdentifierValue(currentValue->id) : nullptr;
@@ -821,7 +820,7 @@
     return true;
 }
 
-RawPtr<CSSValue> CSSPropertyParser::parseGridAutoFlow(CSSParserValueList& list)
+CSSValue* CSSPropertyParser::parseGridAutoFlow(CSSParserValueList& list)
 {
     // [ row | column ] || dense
     ASSERT(RuntimeEnabledFeatures::cssGridLayoutEnabled());
@@ -830,7 +829,7 @@
     if (!value)
         return nullptr;
 
-    RawPtr<CSSValueList> parsedValues = CSSValueList::createSpaceSeparated();
+    CSSValueList* parsedValues = CSSValueList::createSpaceSeparated();
 
     // First parameter.
     CSSValueID firstId = value->id;
diff --git a/third_party/WebKit/Source/core/css/parser/MediaConditionTest.cpp b/third_party/WebKit/Source/core/css/parser/MediaConditionTest.cpp
index 50822b4..abb997d 100644
--- a/third_party/WebKit/Source/core/css/parser/MediaConditionTest.cpp
+++ b/third_party/WebKit/Source/core/css/parser/MediaConditionTest.cpp
@@ -39,7 +39,7 @@
     // FIXME: We should test comma-seperated media conditions
     for (unsigned i = 0; testCases[i].input; ++i) {
         CSSTokenizer::Scope scope(testCases[i].input);
-        RawPtr<MediaQuerySet> mediaConditionQuerySet = MediaQueryParser::parseMediaCondition(scope.tokenRange());
+        MediaQuerySet* mediaConditionQuerySet = MediaQueryParser::parseMediaCondition(scope.tokenRange());
         ASSERT_EQ(mediaConditionQuerySet->queryVector().size(), (unsigned)1);
         String queryText = mediaConditionQuerySet->queryVector()[0]->cssText();
         ASSERT_STREQ(testCases[i].output, queryText.ascii().data());
diff --git a/third_party/WebKit/Source/core/css/parser/MediaQueryParser.cpp b/third_party/WebKit/Source/core/css/parser/MediaQueryParser.cpp
index f1bac52..1b2dbe8 100644
--- a/third_party/WebKit/Source/core/css/parser/MediaQueryParser.cpp
+++ b/third_party/WebKit/Source/core/css/parser/MediaQueryParser.cpp
@@ -11,17 +11,17 @@
 
 namespace blink {
 
-RawPtr<MediaQuerySet> MediaQueryParser::parseMediaQuerySet(const String& queryString)
+MediaQuerySet* MediaQueryParser::parseMediaQuerySet(const String& queryString)
 {
     return parseMediaQuerySet(CSSTokenizer::Scope(queryString).tokenRange());
 }
 
-RawPtr<MediaQuerySet> MediaQueryParser::parseMediaQuerySet(CSSParserTokenRange range)
+MediaQuerySet* MediaQueryParser::parseMediaQuerySet(CSSParserTokenRange range)
 {
     return MediaQueryParser(MediaQuerySetParser).parseImpl(range);
 }
 
-RawPtr<MediaQuerySet> MediaQueryParser::parseMediaCondition(CSSParserTokenRange range)
+MediaQuerySet* MediaQueryParser::parseMediaCondition(CSSParserTokenRange range)
 {
     return MediaQueryParser(MediaConditionParser).parseImpl(range);
 }
@@ -214,7 +214,7 @@
 }
 
 // The state machine loop
-RawPtr<MediaQuerySet> MediaQueryParser::parseImpl(CSSParserTokenRange range)
+MediaQuerySet* MediaQueryParser::parseImpl(CSSParserTokenRange range)
 {
     while (!range.atEnd())
         processToken(range.consume());
@@ -248,18 +248,18 @@
     m_expressions.clear();
 }
 
-RawPtr<MediaQuery> MediaQueryData::takeMediaQuery()
+MediaQuery* MediaQueryData::takeMediaQuery()
 {
-    RawPtr<MediaQuery> mediaQuery = MediaQuery::create(m_restrictor, std::move(m_mediaType), std::move(m_expressions));
+    MediaQuery* mediaQuery = MediaQuery::create(m_restrictor, std::move(m_mediaType), std::move(m_expressions));
     clear();
-    return mediaQuery.release();
+    return mediaQuery;
 }
 
 bool MediaQueryData::addExpression()
 {
-    RawPtr<MediaQueryExp> expression = MediaQueryExp::createIfValid(m_mediaFeature, m_valueList);
+    MediaQueryExp* expression = MediaQueryExp::createIfValid(m_mediaFeature, m_valueList);
     bool isValid = !!expression;
-    m_expressions.append(expression.release());
+    m_expressions.append(expression);
     m_valueList.clear();
     return isValid;
 }
diff --git a/third_party/WebKit/Source/core/css/parser/MediaQueryParser.h b/third_party/WebKit/Source/core/css/parser/MediaQueryParser.h
index bcde4e0..81e1562 100644
--- a/third_party/WebKit/Source/core/css/parser/MediaQueryParser.h
+++ b/third_party/WebKit/Source/core/css/parser/MediaQueryParser.h
@@ -35,7 +35,7 @@
     bool addExpression();
     bool tryAddParserToken(CSSParserTokenType, const CSSParserToken&);
     void setMediaType(const String&);
-    RawPtr<MediaQuery> takeMediaQuery();
+    MediaQuery* takeMediaQuery();
 
     inline bool currentMediaQueryChanged() const
     {
@@ -51,9 +51,9 @@
 class CORE_EXPORT MediaQueryParser {
     STACK_ALLOCATED();
 public:
-    static RawPtr<MediaQuerySet> parseMediaQuerySet(const String&);
-    static RawPtr<MediaQuerySet> parseMediaQuerySet(CSSParserTokenRange);
-    static RawPtr<MediaQuerySet> parseMediaCondition(CSSParserTokenRange);
+    static MediaQuerySet* parseMediaQuerySet(const String&);
+    static MediaQuerySet* parseMediaQuerySet(CSSParserTokenRange);
+    static MediaQuerySet* parseMediaCondition(CSSParserTokenRange);
 
 private:
     enum ParserType {
@@ -64,7 +64,7 @@
     MediaQueryParser(ParserType);
     virtual ~MediaQueryParser();
 
-    RawPtr<MediaQuerySet> parseImpl(CSSParserTokenRange);
+    MediaQuerySet* parseImpl(CSSParserTokenRange);
 
     void processToken(const CSSParserToken&);
 
diff --git a/third_party/WebKit/Source/core/css/parser/SizesAttributeParser.cpp b/third_party/WebKit/Source/core/css/parser/SizesAttributeParser.cpp
index 97cd6de..3a2f1f9 100644
--- a/third_party/WebKit/Source/core/css/parser/SizesAttributeParser.cpp
+++ b/third_party/WebKit/Source/core/css/parser/SizesAttributeParser.cpp
@@ -11,7 +11,7 @@
 
 namespace blink {
 
-SizesAttributeParser::SizesAttributeParser(RawPtr<MediaValues> mediaValues, const String& attribute)
+SizesAttributeParser::SizesAttributeParser(MediaValues* mediaValues, const String& attribute)
     : m_mediaValues(mediaValues)
     , m_length(0)
     , m_lengthWasSet(false)
@@ -53,11 +53,11 @@
     return false;
 }
 
-bool SizesAttributeParser::mediaConditionMatches(RawPtr<MediaQuerySet> mediaCondition)
+bool SizesAttributeParser::mediaConditionMatches(MediaQuerySet* mediaCondition)
 {
     // A Media Condition cannot have a media type other then screen.
     MediaQueryEvaluator mediaQueryEvaluator(*m_mediaValues);
-    return mediaQueryEvaluator.eval(mediaCondition.get());
+    return mediaQueryEvaluator.eval(mediaCondition);
 }
 
 bool SizesAttributeParser::parse(CSSParserTokenRange range)
@@ -79,7 +79,7 @@
         float length;
         if (!calculateLengthInPixels(range.makeSubRange(lengthTokenStart, lengthTokenEnd), length))
             continue;
-        RawPtr<MediaQuerySet> mediaCondition = MediaQueryParser::parseMediaCondition(range.makeSubRange(mediaConditionStart, lengthTokenStart));
+        MediaQuerySet* mediaCondition = MediaQueryParser::parseMediaCondition(range.makeSubRange(mediaConditionStart, lengthTokenStart));
         if (!mediaCondition || !mediaConditionMatches(mediaCondition))
             continue;
         m_length = length;
diff --git a/third_party/WebKit/Source/core/css/parser/SizesAttributeParser.h b/third_party/WebKit/Source/core/css/parser/SizesAttributeParser.h
index f8193e7..2992bae 100644
--- a/third_party/WebKit/Source/core/css/parser/SizesAttributeParser.h
+++ b/third_party/WebKit/Source/core/css/parser/SizesAttributeParser.h
@@ -17,7 +17,7 @@
 class CORE_EXPORT SizesAttributeParser {
     STACK_ALLOCATED();
 public:
-    SizesAttributeParser(RawPtr<MediaValues>, const String&);
+    SizesAttributeParser(MediaValues*, const String&);
 
     float length();
 
@@ -25,7 +25,7 @@
     bool parse(CSSParserTokenRange);
     float effectiveSize();
     bool calculateLengthInPixels(CSSParserTokenRange, float& result);
-    bool mediaConditionMatches(RawPtr<MediaQuerySet> mediaCondition);
+    bool mediaConditionMatches(MediaQuerySet* mediaCondition);
     unsigned effectiveSizeDefaultValue();
 
     Member<MediaQuerySet> m_mediaCondition;
diff --git a/third_party/WebKit/Source/core/css/parser/SizesAttributeParserTest.cpp b/third_party/WebKit/Source/core/css/parser/SizesAttributeParserTest.cpp
index 59c7fdc..52656e80 100644
--- a/third_party/WebKit/Source/core/css/parser/SizesAttributeParserTest.cpp
+++ b/third_party/WebKit/Source/core/css/parser/SizesAttributeParserTest.cpp
@@ -88,7 +88,7 @@
     data.mediaType = MediaTypeNames::screen;
     data.strictMode = true;
     data.displayMode = WebDisplayModeBrowser;
-    RawPtr<MediaValues> mediaValues = MediaValuesCached::create(data);
+    MediaValues* mediaValues = MediaValuesCached::create(data);
 
     for (unsigned i = 0; testCases[i].input; ++i) {
         SizesAttributeParser parser(mediaValues, testCases[i].input);
diff --git a/third_party/WebKit/Source/core/css/parser/SizesCalcParser.cpp b/third_party/WebKit/Source/core/css/parser/SizesCalcParser.cpp
index c712fc4..7a4a61a 100644
--- a/third_party/WebKit/Source/core/css/parser/SizesCalcParser.cpp
+++ b/third_party/WebKit/Source/core/css/parser/SizesCalcParser.cpp
@@ -9,7 +9,7 @@
 
 namespace blink {
 
-SizesCalcParser::SizesCalcParser(CSSParserTokenRange range, RawPtr<MediaValues> mediaValues)
+SizesCalcParser::SizesCalcParser(CSSParserTokenRange range, MediaValues* mediaValues)
     : m_mediaValues(mediaValues)
     , m_result(0)
 {
diff --git a/third_party/WebKit/Source/core/css/parser/SizesCalcParser.h b/third_party/WebKit/Source/core/css/parser/SizesCalcParser.h
index 5d049850..0d365044 100644
--- a/third_party/WebKit/Source/core/css/parser/SizesCalcParser.h
+++ b/third_party/WebKit/Source/core/css/parser/SizesCalcParser.h
@@ -37,7 +37,7 @@
 class CORE_EXPORT SizesCalcParser {
     STACK_ALLOCATED();
 public:
-    SizesCalcParser(CSSParserTokenRange, RawPtr<MediaValues>);
+    SizesCalcParser(CSSParserTokenRange, MediaValues*);
 
     float result() const;
     bool isValid() const { return m_isValid; }
diff --git a/third_party/WebKit/Source/core/css/parser/SizesCalcParserTest.cpp b/third_party/WebKit/Source/core/css/parser/SizesCalcParserTest.cpp
index e69935d..9b9dea4 100644
--- a/third_party/WebKit/Source/core/css/parser/SizesCalcParserTest.cpp
+++ b/third_party/WebKit/Source/core/css/parser/SizesCalcParserTest.cpp
@@ -31,8 +31,8 @@
 {
     CSSLengthArray lengthArray;
     initLengthArray(lengthArray);
-    RawPtr<CSSValue> cssValue = CSSParser::parseSingleValue(CSSPropertyLeft, text);
-    CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(cssValue.get());
+    CSSValue* cssValue = CSSParser::parseSingleValue(CSSPropertyLeft, text);
+    CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(cssValue);
     if (primitiveValue)
         primitiveValue->accumulateLengthArray(lengthArray);
     else
@@ -112,7 +112,7 @@
     data.mediaType = MediaTypeNames::screen;
     data.strictMode = true;
     data.displayMode = WebDisplayModeBrowser;
-    RawPtr<MediaValues> mediaValues = MediaValuesCached::create(data);
+    MediaValues* mediaValues = MediaValuesCached::create(data);
 
     for (unsigned i = 0; testCases[i].input; ++i) {
         SizesCalcParser calcParser(CSSTokenizer::Scope(testCases[i].input).tokenRange(), mediaValues);
diff --git a/third_party/WebKit/Source/core/css/properties/CSSPropertyDescriptor.h b/third_party/WebKit/Source/core/css/properties/CSSPropertyDescriptor.h
index c46da5f..5b97ba7 100644
--- a/third_party/WebKit/Source/core/css/properties/CSSPropertyDescriptor.h
+++ b/third_party/WebKit/Source/core/css/properties/CSSPropertyDescriptor.h
@@ -48,7 +48,7 @@
 
     // Accessors to functions on the property API.
     CSSPropertyID id() const { return m_id; }
-    RawPtr<CSSValue> parseSingleValue(CSSParserTokenRange& range, const CSSParserContext& context) const { return m_parseSingleValue(range, context); }
+    CSSValue* parseSingleValue(CSSParserTokenRange& range, const CSSParserContext& context) const { return m_parseSingleValue(range, context); }
 
 private:
     // Used internally to check whether an array entry is filled or not.
diff --git a/third_party/WebKit/Source/core/css/properties/CSSPropertyFunctions.h b/third_party/WebKit/Source/core/css/properties/CSSPropertyFunctions.h
index 846ef5d..a17b209 100644
--- a/third_party/WebKit/Source/core/css/properties/CSSPropertyFunctions.h
+++ b/third_party/WebKit/Source/core/css/properties/CSSPropertyFunctions.h
@@ -25,7 +25,7 @@
     // Consumes and parses a single value for this property from by the token range,
     // returning the corresponding CSSValue. This function does not check for the end
     // of the token range. Returns nullptr if the input is invalid.
-    static RawPtr<CSSValue> parseSingleValue(CSSParserTokenRange&, const CSSParserContext&);
+    static CSSValue* parseSingleValue(CSSParserTokenRange&, const CSSParserContext&);
     using parseSingleValueFunction = decltype(&parseSingleValue);
 };
 
diff --git a/third_party/WebKit/Source/core/css/resolver/CSSVariableResolver.cpp b/third_party/WebKit/Source/core/css/resolver/CSSVariableResolver.cpp
index 91be435..d45ae959 100644
--- a/third_party/WebKit/Source/core/css/resolver/CSSVariableResolver.cpp
+++ b/third_party/WebKit/Source/core/css/resolver/CSSVariableResolver.cpp
@@ -130,7 +130,7 @@
     return success;
 }
 
-RawPtr<CSSValue> CSSVariableResolver::resolveVariableReferences(StyleVariableData* styleVariableData, CSSPropertyID id, const CSSVariableReferenceValue& value)
+CSSValue* CSSVariableResolver::resolveVariableReferences(StyleVariableData* styleVariableData, CSSPropertyID id, const CSSVariableReferenceValue& value)
 {
     ASSERT(!isShorthandProperty(id));
 
@@ -138,10 +138,10 @@
     Vector<CSSParserToken> tokens;
     if (!resolver.resolveTokenRange(value.variableDataValue()->tokens(), tokens))
         return cssValuePool().createUnsetValue();
-    RawPtr<CSSValue> result = CSSPropertyParser::parseSingleValue(id, tokens, strictCSSParserContext());
+    CSSValue* result = CSSPropertyParser::parseSingleValue(id, tokens, strictCSSParserContext());
     if (!result)
         return cssValuePool().createUnsetValue();
-    return result.release();
+    return result;
 }
 
 void CSSVariableResolver::resolveAndApplyVariableReferences(StyleResolverState& state, CSSPropertyID id, const CSSVariableReferenceValue& value)
@@ -163,15 +163,15 @@
         }
     }
 
-    RawPtr<CSSUnsetValue> unset = cssValuePool().createUnsetValue();
+    CSSUnsetValue* unset = cssValuePool().createUnsetValue();
     if (isShorthandProperty(id)) {
         StylePropertyShorthand shorthand = shorthandForProperty(id);
         for (unsigned i = 0; i < shorthand.length(); i++)
-            StyleBuilder::applyProperty(shorthand.properties()[i], state, unset.get());
+            StyleBuilder::applyProperty(shorthand.properties()[i], state, unset);
         return;
     }
 
-    StyleBuilder::applyProperty(id, state, unset.get());
+    StyleBuilder::applyProperty(id, state, unset);
 }
 
 void CSSVariableResolver::resolveVariableDefinitions(StyleVariableData* variables)
diff --git a/third_party/WebKit/Source/core/css/resolver/CSSVariableResolver.h b/third_party/WebKit/Source/core/css/resolver/CSSVariableResolver.h
index 2aabc55..c1150ff7 100644
--- a/third_party/WebKit/Source/core/css/resolver/CSSVariableResolver.h
+++ b/third_party/WebKit/Source/core/css/resolver/CSSVariableResolver.h
@@ -25,7 +25,7 @@
     static void resolveAndApplyVariableReferences(StyleResolverState&, CSSPropertyID, const CSSVariableReferenceValue&);
 
     // Shorthand properties are not supported.
-    static RawPtr<CSSValue> resolveVariableReferences(StyleVariableData*, CSSPropertyID, const CSSVariableReferenceValue&);
+    static CSSValue* resolveVariableReferences(StyleVariableData*, CSSPropertyID, const CSSVariableReferenceValue&);
 
 private:
     CSSVariableResolver(StyleVariableData*);
diff --git a/third_party/WebKit/Source/core/css/resolver/ElementStyleResources.cpp b/third_party/WebKit/Source/core/css/resolver/ElementStyleResources.cpp
index 118a61e..68935d73 100644
--- a/third_party/WebKit/Source/core/css/resolver/ElementStyleResources.cpp
+++ b/third_party/WebKit/Source/core/css/resolver/ElementStyleResources.cpp
@@ -49,7 +49,7 @@
 {
 }
 
-RawPtr<StyleImage> ElementStyleResources::styleImage(CSSPropertyID property, const CSSValue& value)
+StyleImage* ElementStyleResources::styleImage(CSSPropertyID property, const CSSValue& value)
 {
     if (value.isImageValue())
         return cachedOrPendingFromValue(property, toCSSImageValue(value));
@@ -66,7 +66,7 @@
     return nullptr;
 }
 
-RawPtr<StyleImage> ElementStyleResources::generatedOrPendingFromValue(CSSPropertyID property, const CSSImageGeneratorValue& value)
+StyleImage* ElementStyleResources::generatedOrPendingFromValue(CSSPropertyID property, const CSSImageGeneratorValue& value)
 {
     if (value.isPending()) {
         m_pendingImageProperties.add(property);
@@ -75,7 +75,7 @@
     return StyleGeneratedImage::create(value);
 }
 
-RawPtr<StyleImage> ElementStyleResources::setOrPendingFromValue(CSSPropertyID property, const CSSImageSetValue& value)
+StyleImage* ElementStyleResources::setOrPendingFromValue(CSSPropertyID property, const CSSImageSetValue& value)
 {
     if (value.isCachePending(m_deviceScaleFactor)) {
         m_pendingImageProperties.add(property);
@@ -84,7 +84,7 @@
     return value.cachedImage(m_deviceScaleFactor);
 }
 
-RawPtr<StyleImage> ElementStyleResources::cachedOrPendingFromValue(CSSPropertyID property, const CSSImageValue& value)
+StyleImage* ElementStyleResources::cachedOrPendingFromValue(CSSPropertyID property, const CSSImageValue& value)
 {
     if (value.isCachePending()) {
         m_pendingImageProperties.add(property);
@@ -94,7 +94,7 @@
     return value.cachedImage();
 }
 
-RawPtr<StyleImage> ElementStyleResources::cursorOrPendingFromValue(CSSPropertyID property, const CSSCursorImageValue& value)
+StyleImage* ElementStyleResources::cursorOrPendingFromValue(CSSPropertyID property, const CSSCursorImageValue& value)
 {
     if (value.isCachePending(m_deviceScaleFactor)) {
         m_pendingImageProperties.add(property);
@@ -115,9 +115,9 @@
 
     FilterOperations::FilterOperationVector& filterOperations = computedStyle->mutableFilter().operations();
     for (unsigned i = 0; i < filterOperations.size(); ++i) {
-        RawPtr<FilterOperation> filterOperation = filterOperations.at(i);
+        FilterOperation* filterOperation = filterOperations.at(i);
         if (filterOperation->type() == FilterOperation::REFERENCE) {
-            ReferenceFilterOperation* referenceFilter = toReferenceFilterOperation(filterOperation.get());
+            ReferenceFilterOperation* referenceFilter = toReferenceFilterOperation(filterOperation);
 
             CSSSVGDocumentValue* value = m_pendingSVGDocuments.get(referenceFilter);
             if (!value)
@@ -132,7 +132,7 @@
     }
 }
 
-RawPtr<StyleImage> ElementStyleResources::loadPendingImage(StylePendingImage* pendingImage, CrossOriginAttributeValue crossOrigin)
+StyleImage* ElementStyleResources::loadPendingImage(StylePendingImage* pendingImage, CrossOriginAttributeValue crossOrigin)
 {
     if (CSSImageValue* imageValue = pendingImage->cssImageValue())
         return imageValue->cacheImage(m_document, crossOrigin);
@@ -217,8 +217,8 @@
             if (StyleReflection* reflection = style->boxReflect()) {
                 const NinePieceImage& maskImage = reflection->mask();
                 if (maskImage.image() && maskImage.image()->isPendingImage()) {
-                    RawPtr<StyleImage> loadedImage = loadPendingImage(toStylePendingImage(maskImage.image()));
-                    reflection->setMask(NinePieceImage(loadedImage.release(), maskImage.imageSlices(), maskImage.fill(), maskImage.borderSlices(), maskImage.outset(), maskImage.horizontalRule(), maskImage.verticalRule()));
+                    StyleImage* loadedImage = loadPendingImage(toStylePendingImage(maskImage.image()));
+                    reflection->setMask(NinePieceImage(loadedImage, maskImage.imageSlices(), maskImage.fill(), maskImage.borderSlices(), maskImage.outset(), maskImage.horizontalRule(), maskImage.verticalRule()));
                 }
             }
             break;
diff --git a/third_party/WebKit/Source/core/css/resolver/ElementStyleResources.h b/third_party/WebKit/Source/core/css/resolver/ElementStyleResources.h
index 2a9f722..fd5a9ef 100644
--- a/third_party/WebKit/Source/core/css/resolver/ElementStyleResources.h
+++ b/third_party/WebKit/Source/core/css/resolver/ElementStyleResources.h
@@ -51,22 +51,22 @@
 public:
     ElementStyleResources(Document&, float deviceScaleFactor);
 
-    RawPtr<StyleImage> styleImage(CSSPropertyID, const CSSValue&);
-    RawPtr<StyleImage> cachedOrPendingFromValue(CSSPropertyID, const CSSImageValue&);
-    RawPtr<StyleImage> setOrPendingFromValue(CSSPropertyID, const CSSImageSetValue&);
+    StyleImage* styleImage(CSSPropertyID, const CSSValue&);
+    StyleImage* cachedOrPendingFromValue(CSSPropertyID, const CSSImageValue&);
+    StyleImage* setOrPendingFromValue(CSSPropertyID, const CSSImageSetValue&);
 
     void loadPendingResources(ComputedStyle*);
 
     void addPendingSVGDocument(FilterOperation*, CSSSVGDocumentValue*);
 
 private:
-    RawPtr<StyleImage> cursorOrPendingFromValue(CSSPropertyID, const CSSCursorImageValue&);
-    RawPtr<StyleImage> generatedOrPendingFromValue(CSSPropertyID, const CSSImageGeneratorValue&);
+    StyleImage* cursorOrPendingFromValue(CSSPropertyID, const CSSCursorImageValue&);
+    StyleImage* generatedOrPendingFromValue(CSSPropertyID, const CSSImageGeneratorValue&);
 
     void loadPendingSVGDocuments(ComputedStyle*);
     void loadPendingImages(ComputedStyle*);
 
-    RawPtr<StyleImage> loadPendingImage(StylePendingImage*, CrossOriginAttributeValue = CrossOriginAttributeNotSet);
+    StyleImage* loadPendingImage(StylePendingImage*, CrossOriginAttributeValue = CrossOriginAttributeNotSet);
 
     Member<Document> m_document;
     HashSet<CSSPropertyID> m_pendingImageProperties;
diff --git a/third_party/WebKit/Source/core/css/resolver/FilterOperationResolver.cpp b/third_party/WebKit/Source/core/css/resolver/FilterOperationResolver.cpp
index 66cb157..2ade6a5 100644
--- a/third_party/WebKit/Source/core/css/resolver/FilterOperationResolver.cpp
+++ b/third_party/WebKit/Source/core/css/resolver/FilterOperationResolver.cpp
@@ -138,12 +138,12 @@
             CSSSVGDocumentValue* svgDocumentValue = toCSSSVGDocumentValue(filterValue->item(0));
             KURL url = state.document().completeURL(svgDocumentValue->url());
 
-            RawPtr<ReferenceFilterOperation> operation = ReferenceFilterOperation::create(svgDocumentValue->url(), AtomicString(url.fragmentIdentifier()));
+            ReferenceFilterOperation* operation = ReferenceFilterOperation::create(svgDocumentValue->url(), AtomicString(url.fragmentIdentifier()));
             if (SVGURIReference::isExternalURIReference(svgDocumentValue->url(), state.document())) {
                 if (!svgDocumentValue->loadRequested())
-                    state.elementStyleResources().addPendingSVGDocument(operation.get(), svgDocumentValue);
+                    state.elementStyleResources().addPendingSVGDocument(operation, svgDocumentValue);
                 else if (svgDocumentValue->cachedSVGDocument())
-                    ReferenceFilterBuilder::setDocumentResourceReference(operation.get(), adoptPtr(new DocumentResourceReference(svgDocumentValue->cachedSVGDocument())));
+                    ReferenceFilterBuilder::setDocumentResourceReference(operation, adoptPtr(new DocumentResourceReference(svgDocumentValue->cachedSVGDocument())));
             }
             operations.operations().append(operation);
             continue;
diff --git a/third_party/WebKit/Source/core/css/resolver/FontBuilder.cpp b/third_party/WebKit/Source/core/css/resolver/FontBuilder.cpp
index 261025d..4dcf29c 100644
--- a/third_party/WebKit/Source/core/css/resolver/FontBuilder.cpp
+++ b/third_party/WebKit/Source/core/css/resolver/FontBuilder.cpp
@@ -339,7 +339,7 @@
     fontDescription.setComputedSize(computedSize);
 }
 
-void FontBuilder::createFont(RawPtr<FontSelector> fontSelector, ComputedStyle& style)
+void FontBuilder::createFont(FontSelector* fontSelector, ComputedStyle& style)
 {
     if (!m_flags)
         return;
@@ -382,14 +382,14 @@
 
     updateSpecifiedSize(description, style);
     updateComputedSize(description, style);
-    updateAdjustedSize(description, style, fontSelector.get());
+    updateAdjustedSize(description, style, fontSelector);
 
     style.setFontDescription(description);
     style.font().update(fontSelector);
     m_flags = 0;
 }
 
-void FontBuilder::createFontForDocument(RawPtr<FontSelector> fontSelector, ComputedStyle& documentStyle)
+void FontBuilder::createFontForDocument(FontSelector* fontSelector, ComputedStyle& documentStyle)
 {
     FontDescription fontDescription = FontDescription();
     fontDescription.setLocale(documentStyle.locale());
diff --git a/third_party/WebKit/Source/core/css/resolver/FontBuilder.h b/third_party/WebKit/Source/core/css/resolver/FontBuilder.h
index e49b7fc6..21ee8bfb 100644
--- a/third_party/WebKit/Source/core/css/resolver/FontBuilder.h
+++ b/third_party/WebKit/Source/core/css/resolver/FontBuilder.h
@@ -69,9 +69,9 @@
     void setFontSmoothing(FontSmoothingMode);
 
     // FIXME: These need to just vend a Font object eventually.
-    void createFont(RawPtr<FontSelector>, ComputedStyle&);
+    void createFont(FontSelector*, ComputedStyle&);
 
-    void createFontForDocument(RawPtr<FontSelector>, ComputedStyle&);
+    void createFontForDocument(FontSelector*, ComputedStyle&);
 
     bool fontDirty() const { return m_flags; }
 
diff --git a/third_party/WebKit/Source/core/css/resolver/ScopedStyleResolver.cpp b/third_party/WebKit/Source/core/css/resolver/ScopedStyleResolver.cpp
index a931f65..ede3e41e 100644
--- a/third_party/WebKit/Source/core/css/resolver/ScopedStyleResolver.cpp
+++ b/third_party/WebKit/Source/core/css/resolver/ScopedStyleResolver.cpp
@@ -71,7 +71,7 @@
     CSSFontSelector* cssFontSelector = document.styleEngine().fontSelector();
     const HeapVector<Member<StyleRuleFontFace>> fontFaceRules = ruleSet.fontFaceRules();
     for (auto& fontFaceRule : fontFaceRules) {
-        if (RawPtr<FontFace> fontFace = FontFace::create(&document, fontFaceRule))
+        if (FontFace* fontFace = FontFace::create(&document, fontFaceRule))
             cssFontSelector->fontFaceCache()->add(cssFontSelector, fontFaceRule, fontFace);
     }
     if (fontFaceRules.size())
@@ -129,7 +129,7 @@
     return it->value.get();
 }
 
-void ScopedStyleResolver::addKeyframeStyle(RawPtr<StyleRuleKeyframes> rule)
+void ScopedStyleResolver::addKeyframeStyle(StyleRuleKeyframes* rule)
 {
     AtomicString s(rule->name());
 
@@ -215,12 +215,12 @@
     if (!authorRules.deepCombinatorOrShadowPseudoRules().isEmpty())
         m_hasDeepOrShadowSelector = true;
 
-    RawPtr<RuleSet> ruleSetForScope = RuleSet::create();
-    addRules(ruleSetForScope.get(), authorRules.deepCombinatorOrShadowPseudoRules());
+    RuleSet* ruleSetForScope = RuleSet::create();
+    addRules(ruleSetForScope, authorRules.deepCombinatorOrShadowPseudoRules());
 
     if (!isDocumentScope) {
-        addRules(ruleSetForScope.get(), authorRules.contentPseudoElementRules());
-        addRules(ruleSetForScope.get(), authorRules.slottedPseudoElementRules());
+        addRules(ruleSetForScope, authorRules.contentPseudoElementRules());
+        addRules(ruleSetForScope, authorRules.slottedPseudoElementRules());
     }
 
     if (!m_treeBoundaryCrossingRuleSet) {
@@ -228,7 +228,7 @@
         treeScope().document().styleResolver()->addTreeBoundaryCrossingScope(treeScope().rootNode());
     }
 
-    m_treeBoundaryCrossingRuleSet->append(RuleSubSet::create(parentStyleSheet, sheetIndex, ruleSetForScope.release()));
+    m_treeBoundaryCrossingRuleSet->append(RuleSubSet::create(parentStyleSheet, sheetIndex, ruleSetForScope));
 }
 
 DEFINE_TRACE(ScopedStyleResolver::RuleSubSet)
diff --git a/third_party/WebKit/Source/core/css/resolver/ScopedStyleResolver.h b/third_party/WebKit/Source/core/css/resolver/ScopedStyleResolver.h
index 6cf9c54..adf8f418 100644
--- a/third_party/WebKit/Source/core/css/resolver/ScopedStyleResolver.h
+++ b/third_party/WebKit/Source/core/css/resolver/ScopedStyleResolver.h
@@ -45,7 +45,7 @@
 class ScopedStyleResolver final : public GarbageCollected<ScopedStyleResolver> {
     WTF_MAKE_NONCOPYABLE(ScopedStyleResolver);
 public:
-    static RawPtr<ScopedStyleResolver> create(TreeScope& scope)
+    static ScopedStyleResolver* create(TreeScope& scope)
     {
         return new ScopedStyleResolver(scope);
     }
@@ -76,7 +76,7 @@
     void addTreeBoundaryCrossingRules(const RuleSet&, CSSStyleSheet*, unsigned sheetIndex);
     void addKeyframeRules(const RuleSet&);
     void addFontFaceRules(const RuleSet&);
-    void addKeyframeStyle(RawPtr<StyleRuleKeyframes>);
+    void addKeyframeStyle(StyleRuleKeyframes*);
 
     Member<TreeScope> m_scope;
 
@@ -87,7 +87,7 @@
 
     class RuleSubSet final : public GarbageCollected<RuleSubSet> {
     public:
-        static RawPtr<RuleSubSet> create(CSSStyleSheet* sheet, unsigned index, RawPtr<RuleSet> rules)
+        static RuleSubSet* create(CSSStyleSheet* sheet, unsigned index, RuleSet* rules)
         {
             return new RuleSubSet(sheet, index, rules);
         }
@@ -99,7 +99,7 @@
         DECLARE_TRACE();
 
     private:
-        RuleSubSet(CSSStyleSheet* sheet, unsigned index, RawPtr<RuleSet> rules)
+        RuleSubSet(CSSStyleSheet* sheet, unsigned index, RuleSet* rules)
             : m_parentStyleSheet(sheet)
             , m_parentIndex(index)
             , m_ruleSet(rules)
diff --git a/third_party/WebKit/Source/core/css/resolver/StyleBuilderConverter.cpp b/third_party/WebKit/Source/core/css/resolver/StyleBuilderConverter.cpp
index f88701ee..1a3da35 100644
--- a/third_party/WebKit/Source/core/css/resolver/StyleBuilderConverter.cpp
+++ b/third_party/WebKit/Source/core/css/resolver/StyleBuilderConverter.cpp
@@ -793,7 +793,7 @@
     return ShadowList::adopt(shadows);
 }
 
-RawPtr<ShapeValue> StyleBuilderConverter::convertShapeValue(StyleResolverState& state, const CSSValue& value)
+ShapeValue* StyleBuilderConverter::convertShapeValue(StyleResolverState& state, const CSSValue& value)
 {
     if (value.isPrimitiveValue()) {
         ASSERT(toCSSPrimitiveValue(value).getValueID() == CSSValueNone);
diff --git a/third_party/WebKit/Source/core/css/resolver/StyleBuilderConverter.h b/third_party/WebKit/Source/core/css/resolver/StyleBuilderConverter.h
index b0bfc08..7c7fbe5 100644
--- a/third_party/WebKit/Source/core/css/resolver/StyleBuilderConverter.h
+++ b/third_party/WebKit/Source/core/css/resolver/StyleBuilderConverter.h
@@ -89,7 +89,7 @@
     static LengthSize convertRadius(StyleResolverState&, const CSSValue&);
     static EPaintOrder convertPaintOrder(StyleResolverState&, const CSSValue&);
     static PassRefPtr<ShadowList> convertShadow(StyleResolverState&, const CSSValue&);
-    static RawPtr<ShapeValue> convertShapeValue(StyleResolverState&, const CSSValue&);
+    static ShapeValue* convertShapeValue(StyleResolverState&, const CSSValue&);
     static float convertSpacing(StyleResolverState&, const CSSValue&);
     template <CSSValueID IdForNone> static AtomicString convertString(StyleResolverState&, const CSSValue&);
     static PassRefPtr<SVGDashArray> convertStrokeDasharray(StyleResolverState&, const CSSValue&);
diff --git a/third_party/WebKit/Source/core/css/resolver/StyleResolver.cpp b/third_party/WebKit/Source/core/css/resolver/StyleResolver.cpp
index fae3e66..9d1221c 100644
--- a/third_party/WebKit/Source/core/css/resolver/StyleResolver.cpp
+++ b/third_party/WebKit/Source/core/css/resolver/StyleResolver.cpp
@@ -313,15 +313,15 @@
     treeScope.clearScopedStyleResolver();
 }
 
-static RawPtr<RuleSet> makeRuleSet(const HeapVector<RuleFeature>& rules)
+static RuleSet* makeRuleSet(const HeapVector<RuleFeature>& rules)
 {
     size_t size = rules.size();
     if (!size)
         return nullptr;
-    RawPtr<RuleSet> ruleSet = RuleSet::create();
+    RuleSet* ruleSet = RuleSet::create();
     for (size_t i = 0; i < size; ++i)
         ruleSet->addRule(rules[i].rule, rules[i].selectorIndex, rules[i].hasDocumentSecurityOrigin ? RuleHasDocumentSecurityOrigin : RuleHasNoSpecialState);
-    return ruleSet.release();
+    return ruleSet;
 }
 
 void StyleResolver::collectFeatures()
@@ -858,14 +858,14 @@
     return CSSAnimatableValueFactory::create(property, *state.style());
 }
 
-RawPtr<PseudoElement> StyleResolver::createPseudoElement(Element* parent, PseudoId pseudoId)
+PseudoElement* StyleResolver::createPseudoElement(Element* parent, PseudoId pseudoId)
 {
     if (pseudoId == PseudoIdFirstLetter)
         return FirstLetterPseudoElement::create(parent);
     return PseudoElement::create(parent, pseudoId);
 }
 
-RawPtr<PseudoElement> StyleResolver::createPseudoElementIfNeeded(Element& parent, PseudoId pseudoId)
+PseudoElement* StyleResolver::createPseudoElementIfNeeded(Element& parent, PseudoId pseudoId)
 {
     LayoutObject* parentLayoutObject = parent.layoutObject();
     if (!parentLayoutObject)
@@ -902,12 +902,12 @@
     if (!pseudoElementLayoutObjectIsNeeded(style.get()))
         return nullptr;
 
-    RawPtr<PseudoElement> pseudo = createPseudoElement(&parent, pseudoId);
+    PseudoElement* pseudo = createPseudoElement(&parent, pseudoId);
 
     setAnimationUpdateIfNeeded(state, *pseudo);
     if (ElementAnimations* elementAnimations = pseudo->elementAnimations())
-        elementAnimations->cssAnimations().maybeApplyPendingUpdate(pseudo.get());
-    return pseudo.release();
+        elementAnimations->cssAnimations().maybeApplyPendingUpdate(pseudo);
+    return pseudo;
 }
 
 bool StyleResolver::pseudoStyleForElementInternal(Element& element, const PseudoStyleRequest& pseudoStyleRequest, const ComputedStyle* parentStyle, StyleResolverState& state)
@@ -1061,7 +1061,7 @@
     state.setConversionZoom(state.style()->effectiveZoom());
 }
 
-RawPtr<StyleRuleList> StyleResolver::styleRulesForElement(Element* element, unsigned rulesToInclude)
+StyleRuleList* StyleResolver::styleRulesForElement(Element* element, unsigned rulesToInclude)
 {
     ASSERT(element);
     StyleResolverState state(document(), element);
@@ -1071,7 +1071,7 @@
     return collector.matchedStyleRuleList();
 }
 
-RawPtr<CSSRuleList> StyleResolver::pseudoCSSRulesForElement(Element* element, PseudoId pseudoId, unsigned rulesToInclude)
+CSSRuleList* StyleResolver::pseudoCSSRulesForElement(Element* element, PseudoId pseudoId, unsigned rulesToInclude)
 {
     ASSERT(element);
     StyleResolverState state(document(), element);
@@ -1081,7 +1081,7 @@
     return collector.matchedCSSRuleList();
 }
 
-RawPtr<CSSRuleList> StyleResolver::cssRulesForElement(Element* element, unsigned rulesToInclude)
+CSSRuleList* StyleResolver::cssRulesForElement(Element* element, unsigned rulesToInclude)
 {
     return pseudoCSSRulesForElement(element, PseudoIdNone, rulesToInclude);
 }
@@ -1662,7 +1662,7 @@
     collector.collectMatchingRules(matchRequest);
     collector.sortAndTransferMatchedRules();
 
-    RawPtr<StyleRuleList> rules = collector.matchedStyleRuleList();
+    StyleRuleList* rules = collector.matchedStyleRuleList();
     if (!rules)
         return;
     for (size_t i = 0; i < rules->size(); i++)
@@ -1688,7 +1688,7 @@
     for (CSSPropertyID property : properties) {
         if (property == CSSPropertyLineHeight)
             updateFont(state);
-        StyleBuilder::applyProperty(property, state, propertySet.getPropertyCSSValue(property).get());
+        StyleBuilder::applyProperty(property, state, propertySet.getPropertyCSSValue(property));
     }
 }
 
diff --git a/third_party/WebKit/Source/core/css/resolver/StyleResolver.h b/third_party/WebKit/Source/core/css/resolver/StyleResolver.h
index d35639b8..5ce00ae 100644
--- a/third_party/WebKit/Source/core/css/resolver/StyleResolver.h
+++ b/third_party/WebKit/Source/core/css/resolver/StyleResolver.h
@@ -79,7 +79,7 @@
 class CORE_EXPORT StyleResolver final : public GarbageCollectedFinalized<StyleResolver> {
     WTF_MAKE_NONCOPYABLE(StyleResolver);
 public:
-    static RawPtr<StyleResolver> create(Document& document)
+    static StyleResolver* create(Document& document)
     {
         return new StyleResolver(document);
     }
@@ -126,9 +126,9 @@
         AllButEmptyCSSRules = UAAndUserCSSRules | AuthorCSSRules | CrossOriginCSSRules,
         AllCSSRules         = AllButEmptyCSSRules | EmptyCSSRules,
     };
-    RawPtr<CSSRuleList> cssRulesForElement(Element*, unsigned rulesToInclude = AllButEmptyCSSRules);
-    RawPtr<CSSRuleList> pseudoCSSRulesForElement(Element*, PseudoId, unsigned rulesToInclude = AllButEmptyCSSRules);
-    RawPtr<StyleRuleList> styleRulesForElement(Element*, unsigned rulesToInclude);
+    CSSRuleList* cssRulesForElement(Element*, unsigned rulesToInclude = AllButEmptyCSSRules);
+    CSSRuleList* pseudoCSSRulesForElement(Element*, PseudoId, unsigned rulesToInclude = AllButEmptyCSSRules);
+    StyleRuleList* styleRulesForElement(Element*, unsigned rulesToInclude);
 
     void computeFont(ComputedStyle*, const StylePropertySet&);
 
@@ -171,7 +171,7 @@
     void increaseStyleSharingDepth() { ++m_styleSharingDepth; }
     void decreaseStyleSharingDepth() { --m_styleSharingDepth; }
 
-    RawPtr<PseudoElement> createPseudoElementIfNeeded(Element& parent, PseudoId);
+    PseudoElement* createPseudoElementIfNeeded(Element& parent, PseudoId);
 
     DECLARE_TRACE();
 
@@ -220,7 +220,7 @@
     bool hasAuthorBackground(const StyleResolverState&);
     bool hasAuthorBorder(const StyleResolverState&);
 
-    RawPtr<PseudoElement> createPseudoElement(Element* parent, PseudoId);
+    PseudoElement* createPseudoElement(Element* parent, PseudoId);
 
     Document& document() { return *m_document; }
 
diff --git a/third_party/WebKit/Source/core/css/resolver/StyleResolverState.h b/third_party/WebKit/Source/core/css/resolver/StyleResolverState.h
index c6d88639..547e58a 100644
--- a/third_party/WebKit/Source/core/css/resolver/StyleResolverState.h
+++ b/third_party/WebKit/Source/core/css/resolver/StyleResolverState.h
@@ -118,7 +118,7 @@
     // FIXME: Once styleImage can be made to not take a StyleResolverState
     // this convenience function should be removed. As-is, without this, call
     // sites are extremely verbose.
-    RawPtr<StyleImage> styleImage(CSSPropertyID propertyId, const CSSValue& value)
+    StyleImage* styleImage(CSSPropertyID propertyId, const CSSValue& value)
     {
         return m_elementStyleResources.styleImage(propertyId, value);
     }
diff --git a/third_party/WebKit/Source/core/css/resolver/ViewportStyleResolver.cpp b/third_party/WebKit/Source/core/css/resolver/ViewportStyleResolver.cpp
index 8f90de9..8cc01eb 100644
--- a/third_party/WebKit/Source/core/css/resolver/ViewportStyleResolver.cpp
+++ b/third_party/WebKit/Source/core/css/resolver/ViewportStyleResolver.cpp
@@ -133,11 +133,11 @@
     if (id == CSSPropertyUserZoom)
         defaultValue = 1;
 
-    RawPtr<CSSValue> value = m_propertySet->getPropertyCSSValue(id);
+    CSSValue* value = m_propertySet->getPropertyCSSValue(id);
     if (!value || !value->isPrimitiveValue())
         return defaultValue;
 
-    CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value.get());
+    CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
 
     if (primitiveValue->isNumber() || primitiveValue->isPx())
         return primitiveValue->getFloatValue();
@@ -183,11 +183,11 @@
         || id == CSSPropertyMaxWidth
         || id == CSSPropertyMinWidth);
 
-    RawPtr<CSSValue> value = m_propertySet->getPropertyCSSValue(id);
+    CSSValue* value = m_propertySet->getPropertyCSSValue(id);
     if (!value || !value->isPrimitiveValue())
         return Length(); // auto
 
-    CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value.get());
+    CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
 
     if (primitiveValue->getValueID() == CSSValueInternalExtendToZoom)
         return Length(ExtendToZoom);
diff --git a/third_party/WebKit/Source/core/css/resolver/ViewportStyleResolver.h b/third_party/WebKit/Source/core/css/resolver/ViewportStyleResolver.h
index 78b1568..30ad5fc 100644
--- a/third_party/WebKit/Source/core/css/resolver/ViewportStyleResolver.h
+++ b/third_party/WebKit/Source/core/css/resolver/ViewportStyleResolver.h
@@ -45,7 +45,7 @@
 
 class CORE_EXPORT ViewportStyleResolver : public GarbageCollected<ViewportStyleResolver> {
 public:
-    static RawPtr<ViewportStyleResolver> create(Document* document)
+    static ViewportStyleResolver* create(Document* document)
     {
         return new ViewportStyleResolver(document);
     }
diff --git a/third_party/WebKit/Source/core/dom/ChildFrameDisconnector.cpp b/third_party/WebKit/Source/core/dom/ChildFrameDisconnector.cpp
index f34818c..9a7ec21 100644
--- a/third_party/WebKit/Source/core/dom/ChildFrameDisconnector.cpp
+++ b/third_party/WebKit/Source/core/dom/ChildFrameDisconnector.cpp
@@ -60,7 +60,7 @@
         HTMLFrameOwnerElement* owner = m_frameOwners[i].get();
         // Don't need to traverse up the tree for the first owner since no
         // script could have moved it.
-        if (!i || root().containsIncludingShadowDOM(owner))
+        if (!i || root().isShadowIncludingInclusiveAncestorOf(owner))
             owner->disconnectContentFrame();
     }
 }
diff --git a/third_party/WebKit/Source/core/dom/ContainerNode.cpp b/third_party/WebKit/Source/core/dom/ContainerNode.cpp
index 5d5b12b..d698d6a 100644
--- a/third_party/WebKit/Source/core/dom/ContainerNode.cpp
+++ b/third_party/WebKit/Source/core/dom/ContainerNode.cpp
@@ -514,7 +514,7 @@
             next->setPreviousSibling(nullptr);
 
         if (!n->refCount()) {
-            if (n->inDocument())
+            if (n->inShadowIncludingDocument())
                 container.document().decrementNodeCount();
 
 #if ENABLE(SECURITY_ASSERT)
@@ -531,7 +531,7 @@
         } else {
             RawPtr<Node> protect(n); // removedFromDocument may remove all references to this node.
             container.document().adoptIfNeeded(*n);
-            if (n->inDocument())
+            if (n->inShadowIncludingDocument())
                 container.notifyNodeRemoved(*n);
         }
     }
@@ -830,7 +830,7 @@
     childrenChanged(ChildrenChange::forInsertion(root, source));
 
     for (const auto& targetNode : postInsertionNotificationTargets) {
-        if (targetNode->inDocument())
+        if (targetNode->inShadowIncludingDocument())
             targetNode->didNotifySubtreeInsertionsToDocument();
     }
 }
@@ -843,7 +843,7 @@
     for (Node& node : NodeTraversal::inclusiveDescendantsOf(root)) {
         // As an optimization we don't notify leaf nodes when when inserting
         // into detached subtrees that are not in a shadow tree.
-        if (!inDocument() && !isInShadowTree() && !node.isContainerNode())
+        if (!inShadowIncludingDocument() && !isInShadowTree() && !node.isContainerNode())
             continue;
         if (Node::InsertionShouldCallDidNotifySubtreeInsertions == node.insertedInto(this))
             postInsertionNotificationTargets.append(&node);
@@ -1248,7 +1248,7 @@
         c->dispatchScopedEvent(MutationEvent::create(EventTypeNames::DOMNodeInserted, true, c->parentNode()));
 
     // dispatch the DOMNodeInsertedIntoDocument event to all descendants
-    if (c->inDocument() && document->hasListenerType(Document::DOMNODEINSERTEDINTODOCUMENT_LISTENER)) {
+    if (c->inShadowIncludingDocument() && document->hasListenerType(Document::DOMNODEINSERTEDINTODOCUMENT_LISTENER)) {
         for (; c; c = NodeTraversal::next(*c, &child))
             c->dispatchScopedEvent(MutationEvent::create(EventTypeNames::DOMNodeInsertedIntoDocument, false));
     }
@@ -1275,7 +1275,7 @@
     }
 
     // Dispatch the DOMNodeRemovedFromDocument event to all descendants.
-    if (c->inDocument() && document->hasListenerType(Document::DOMNODEREMOVEDFROMDOCUMENT_LISTENER)) {
+    if (c->inShadowIncludingDocument() && document->hasListenerType(Document::DOMNODEREMOVEDFROMDOCUMENT_LISTENER)) {
         NodeChildRemovalTracker scope(child);
         for (; c; c = NodeTraversal::next(*c, &child))
             c->dispatchScopedEvent(MutationEvent::create(EventTypeNames::DOMNodeRemovedFromDocument, false));
diff --git a/third_party/WebKit/Source/core/dom/Document.cpp b/third_party/WebKit/Source/core/dom/Document.cpp
index 1f7d4b98..1e74e399 100644
--- a/third_party/WebKit/Source/core/dom/Document.cpp
+++ b/third_party/WebKit/Source/core/dom/Document.cpp
@@ -1928,7 +1928,7 @@
         return false;
     if (!needsLayoutTreeUpdate())
         return false;
-    if (!node.inDocument())
+    if (!node.inShadowIncludingDocument())
         return false;
 
     if (needsFullLayoutTreeUpdate() || node.needsStyleRecalc() || node.needsStyleInvalidation())
@@ -3541,9 +3541,9 @@
         return;
 
     // We can't be focused if we're not in the document.
-    if (!node->inDocument())
+    if (!node->inShadowIncludingDocument())
         return;
-    bool contains = node->containsIncludingShadowDOM(m_focusedElement.get());
+    bool contains = node->isShadowIncludingInclusiveAncestorOf(m_focusedElement.get());
     if (contains && (m_focusedElement != node || !amongChildrenOnly))
         clearFocusedElement();
 }
diff --git a/third_party/WebKit/Source/core/dom/Element.cpp b/third_party/WebKit/Source/core/dom/Element.cpp
index 63df73d..3725831b 100644
--- a/third_party/WebKit/Source/core/dom/Element.cpp
+++ b/third_party/WebKit/Source/core/dom/Element.cpp
@@ -1179,7 +1179,7 @@
     if (!document().styleResolver())
         setNeedsStyleRecalc(SubtreeStyleChange, StyleChangeReasonForTracing::fromAttribute(name));
 
-    if (inDocument()) {
+    if (inShadowIncludingDocument()) {
         if (AXObjectCache* cache = document().existingAXObjectCache())
             cache->handleAttributeChanged(name, this);
     }
@@ -1330,7 +1330,7 @@
 
 void Element::parserSetAttributes(const Vector<Attribute>& attributeVector)
 {
-    ASSERT(!inDocument());
+    ASSERT(!inShadowIncludingDocument());
     ASSERT(!parentNode());
     ASSERT(!m_elementData);
 
@@ -1400,7 +1400,7 @@
 
 Node::InsertionNotificationRequest Element::insertedInto(ContainerNode* insertionPoint)
 {
-    // need to do superclass processing first so inDocument() is true
+    // need to do superclass processing first so inShadowIncludingDocument() is true
     // by the time we reach updateId
     ContainerNode::insertedInto(insertionPoint);
 
@@ -1419,7 +1419,7 @@
             rareData->intersectionObserverData()->activateValidIntersectionObservers(*this);
     }
 
-    if (isUpgradedCustomElement() && inDocument())
+    if (isUpgradedCustomElement() && inShadowIncludingDocument())
         CustomElement::didAttach(this, document());
 
     TreeScope& scope = insertionPoint->treeScope();
@@ -1442,7 +1442,7 @@
 
 void Element::removedFrom(ContainerNode* insertionPoint)
 {
-    bool wasInDocument = insertionPoint->inDocument();
+    bool wasInDocument = insertionPoint->inShadowIncludingDocument();
 
     ASSERT(!hasRareData() || !elementRareData()->hasPseudoElements());
 
@@ -2350,7 +2350,7 @@
 
 void Element::focus(const FocusParams& params)
 {
-    if (!inDocument())
+    if (!inShadowIncludingDocument())
         return;
 
     if (document().focusedElement() == this)
@@ -2364,12 +2364,12 @@
         return;
 
     if (authorShadowRoot() && authorShadowRoot()->delegatesFocus()) {
-        if (containsIncludingShadowDOM(document().focusedElement()))
+        if (isShadowIncludingInclusiveAncestorOf(document().focusedElement()))
             return;
 
         // Slide the focus to its inner node.
         Element* found = document().page()->focusController().findFocusableElementInShadowHost(*this);
-        if (found && containsIncludingShadowDOM(found)) {
+        if (found && isShadowIncludingInclusiveAncestorOf(found)) {
             found->focus(FocusParams(SelectionBehaviorOnFocus::Reset, WebFocusTypeForward, nullptr));
             return;
         }
@@ -2465,7 +2465,7 @@
     // Style cannot be cleared out for non-active documents, so in that case the
     // needsLayoutTreeUpdateForNode check is invalid.
     ASSERT(!document().isActive() || !document().needsLayoutTreeUpdateForNode(*this));
-    return inDocument() && supportsFocus() && !isInert() && layoutObjectIsFocusable();
+    return inShadowIncludingDocument() && supportsFocus() && !isInert() && layoutObjectIsFocusable();
 }
 
 bool Element::isKeyboardFocusable() const
@@ -2519,8 +2519,7 @@
 
 void Element::setInnerHTML(const String& html, ExceptionState& exceptionState)
 {
-    InspectorInstrumentation::willSetInnerHTML(this);
-
+    InspectorInstrumentation::allowNativeBreakpoint(&document(), "setInnerHTML", true);
     if (RawPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(html, this, AllowScriptingContent, "innerHTML", exceptionState)) {
         ContainerNode* container = this;
         if (isHTMLTemplateElement(*this))
@@ -2649,7 +2648,7 @@
     if (document().frame()) {
         if (!document().frame()->eventHandler().isPointerEventActive(pointerId))
             exceptionState.throwDOMException(InvalidPointerId, "InvalidPointerId");
-        else if (!inDocument())
+        else if (!inShadowIncludingDocument())
             exceptionState.throwDOMException(InvalidStateError, "InvalidStateError");
         // TODO(crbug.com/579553): This next "else if" is a hack to notify JS that we don't (yet) support
         // explicit set/release of touch pointers (which are implicitly captured for performance reasons).
@@ -3120,7 +3119,7 @@
 
 inline void Element::updateName(const AtomicString& oldName, const AtomicString& newName)
 {
-    if (!inDocument() || isInShadowTree())
+    if (!inShadowIncludingDocument() || isInShadowTree())
         return;
 
     if (oldName == newName)
@@ -3618,7 +3617,7 @@
 
 void Element::logAddElementIfIsolatedWorldAndInDocument(const char element[], const QualifiedName& attr1)
 {
-    if (!inDocument())
+    if (!inShadowIncludingDocument())
         return;
     V8DOMActivityLogger* activityLogger = V8DOMActivityLogger::currentActivityLoggerIfIsolatedWorld();
     if (!activityLogger)
@@ -3631,7 +3630,7 @@
 
 void Element::logAddElementIfIsolatedWorldAndInDocument(const char element[], const QualifiedName& attr1, const QualifiedName& attr2)
 {
-    if (!inDocument())
+    if (!inShadowIncludingDocument())
         return;
     V8DOMActivityLogger* activityLogger = V8DOMActivityLogger::currentActivityLoggerIfIsolatedWorld();
     if (!activityLogger)
@@ -3645,7 +3644,7 @@
 
 void Element::logAddElementIfIsolatedWorldAndInDocument(const char element[], const QualifiedName& attr1, const QualifiedName& attr2, const QualifiedName& attr3)
 {
-    if (!inDocument())
+    if (!inShadowIncludingDocument())
         return;
     V8DOMActivityLogger* activityLogger = V8DOMActivityLogger::currentActivityLoggerIfIsolatedWorld();
     if (!activityLogger)
@@ -3660,7 +3659,7 @@
 
 void Element::logUpdateAttributeIfIsolatedWorldAndInDocument(const char element[], const QualifiedName& attributeName, const AtomicString& oldValue, const AtomicString& newValue)
 {
-    if (!inDocument())
+    if (!inShadowIncludingDocument())
         return;
     V8DOMActivityLogger* activityLogger = V8DOMActivityLogger::currentActivityLoggerIfIsolatedWorld();
     if (!activityLogger)
diff --git a/third_party/WebKit/Source/core/dom/Element.h b/third_party/WebKit/Source/core/dom/Element.h
index 6203c0a..e728896 100644
--- a/third_party/WebKit/Source/core/dom/Element.h
+++ b/third_party/WebKit/Source/core/dom/Element.h
@@ -551,7 +551,7 @@
     uint32_t compositorMutableProperties() const;
 
     // Helpers for V8DOMActivityLogger::logEvent.  They call logEvent only if
-    // the element is inDocument() and the context is an isolated world.
+    // the element is inShadowIncludingDocument() and the context is an isolated world.
     void logAddElementIfIsolatedWorldAndInDocument(const char element[], const QualifiedName& attr1);
     void logAddElementIfIsolatedWorldAndInDocument(const char element[], const QualifiedName& attr1, const QualifiedName& attr2);
     void logAddElementIfIsolatedWorldAndInDocument(const char element[], const QualifiedName& attr1, const QualifiedName& attr2, const QualifiedName& attr3);
@@ -849,8 +849,8 @@
 {
     ASSERT(!childNeedsStyleInvalidation());
     ASSERT(!needsStyleInvalidation());
-    ASSERT(insertionPoint->inDocument() || insertionPoint->isInShadowTree() || isContainerNode());
-    if (insertionPoint->inDocument()) {
+    ASSERT(insertionPoint->inShadowIncludingDocument() || insertionPoint->isInShadowTree() || isContainerNode());
+    if (insertionPoint->inShadowIncludingDocument()) {
         setFlag(InDocumentFlag);
         insertionPoint->document().incrementNodeCount();
     }
@@ -863,8 +863,8 @@
 
 inline void Node::removedFrom(ContainerNode* insertionPoint)
 {
-    ASSERT(insertionPoint->inDocument() || isContainerNode() || isInShadowTree());
-    if (insertionPoint->inDocument()) {
+    ASSERT(insertionPoint->inShadowIncludingDocument() || isContainerNode() || isInShadowTree());
+    if (insertionPoint->inShadowIncludingDocument()) {
         clearFlag(InDocumentFlag);
         insertionPoint->document().decrementNodeCount();
     }
diff --git a/third_party/WebKit/Source/core/dom/FrameRequestCallbackCollection.cpp b/third_party/WebKit/Source/core/dom/FrameRequestCallbackCollection.cpp
index 94afac1..d716fd9e 100644
--- a/third_party/WebKit/Source/core/dom/FrameRequestCallbackCollection.cpp
+++ b/third_party/WebKit/Source/core/dom/FrameRequestCallbackCollection.cpp
@@ -23,9 +23,8 @@
     m_callbacks.append(callback);
 
     TRACE_EVENT_INSTANT1("devtools.timeline", "RequestAnimationFrame", TRACE_EVENT_SCOPE_THREAD, "data", InspectorAnimationFrameEvent::data(m_context, id));
-    InspectorInstrumentation::didRequestAnimationFrame(m_context, id);
     InspectorInstrumentation::asyncTaskScheduled(m_context, "requestAnimationFrame", callback);
-
+    InspectorInstrumentation::allowNativeBreakpoint(m_context, "requestAnimationFrame", true);
     return id;
 }
 
@@ -34,17 +33,17 @@
     for (size_t i = 0; i < m_callbacks.size(); ++i) {
         if (m_callbacks[i]->m_id == id) {
             InspectorInstrumentation::asyncTaskCanceled(m_context, m_callbacks[i]);
+            InspectorInstrumentation::allowNativeBreakpoint(m_context, "cancelAnimationFrame", true);
             m_callbacks.remove(i);
             TRACE_EVENT_INSTANT1("devtools.timeline", "CancelAnimationFrame", TRACE_EVENT_SCOPE_THREAD, "data", InspectorAnimationFrameEvent::data(m_context, id));
-            InspectorInstrumentation::didCancelAnimationFrame(m_context, id);
             return;
         }
     }
     for (size_t i = 0; i < m_callbacksToInvoke.size(); ++i) {
         if (m_callbacksToInvoke[i]->m_id == id) {
             InspectorInstrumentation::asyncTaskCanceled(m_context, m_callbacksToInvoke[i]);
+            InspectorInstrumentation::allowNativeBreakpoint(m_context, "cancelAnimationFrame", true);
             TRACE_EVENT_INSTANT1("devtools.timeline", "CancelAnimationFrame", TRACE_EVENT_SCOPE_THREAD, "data", InspectorAnimationFrameEvent::data(m_context, id));
-            InspectorInstrumentation::didCancelAnimationFrame(m_context, id);
             m_callbacksToInvoke[i]->m_cancelled = true;
             // will be removed at the end of executeCallbacks()
             return;
@@ -63,6 +62,7 @@
         FrameRequestCallback* callback = m_callbacksToInvoke[i].get();
         if (!callback->m_cancelled) {
             TRACE_EVENT1("devtools.timeline", "FireAnimationFrame", "data", InspectorAnimationFrameEvent::data(m_context, callback->m_id));
+            InspectorInstrumentation::allowNativeBreakpoint(m_context, "animationFrameFired", false);
             InspectorInstrumentation::AsyncTask asyncTask(m_context, callback);
             if (callback->m_useLegacyTimeBase)
                 callback->handleEvent(highResNowMsLegacy);
diff --git a/third_party/WebKit/Source/core/dom/Fullscreen.cpp b/third_party/WebKit/Source/core/dom/Fullscreen.cpp
index a51865e..8c710b2 100644
--- a/third_party/WebKit/Source/core/dom/Fullscreen.cpp
+++ b/third_party/WebKit/Source/core/dom/Fullscreen.cpp
@@ -85,7 +85,7 @@
     // following are true, and false otherwise:
 
     // |element| is in a document.
-    if (!element.inDocument())
+    if (!element.inShadowIncludingDocument())
         return false;
 
     // |element|'s node document's fullscreen enabled flag is set.
@@ -362,7 +362,7 @@
         //    If doc's fullscreen element stack is non-empty and the element now at the top is either
         //    not in a document or its node document is not doc, repeat this substep.
         newTop = fullscreenElementFrom(*currentDoc);
-        if (newTop && (!newTop->inDocument() || newTop->document() != currentDoc))
+        if (newTop && (!newTop->inShadowIncludingDocument() || newTop->document() != currentDoc))
             continue;
 
         // 2. Queue a task to fire an event named fullscreenchange with its bubbles attribute set to true
@@ -558,7 +558,7 @@
         Node* target = event->target()->toNode();
 
         // If the element was removed from our tree, also message the documentElement.
-        if (!target->inDocument() && document()->documentElement()) {
+        if (!target->inShadowIncludingDocument() && document()->documentElement()) {
             ASSERT(isPrefixed(event->type()));
             eventQueue.append(createEvent(event->type(), *document()->documentElement()));
         }
diff --git a/third_party/WebKit/Source/core/dom/IntersectionObservation.cpp b/third_party/WebKit/Source/core/dom/IntersectionObservation.cpp
index 3ecc33a..454cbe00 100644
--- a/third_party/WebKit/Source/core/dom/IntersectionObservation.cpp
+++ b/third_party/WebKit/Source/core/dom/IntersectionObservation.cpp
@@ -151,7 +151,7 @@
     // the IntersectionObservation alive).  During that interval, we need to check that m_target
     // hasn't been cleared.
     Element* targetElement = target();
-    if (!targetElement || !targetElement->inDocument())
+    if (!targetElement || !targetElement->inShadowIncludingDocument())
         return false;
     LayoutObject* targetLayoutObject = targetElement->layoutObject();
     ASSERT(m_observer);
diff --git a/third_party/WebKit/Source/core/dom/IntersectionObserver.cpp b/third_party/WebKit/Source/core/dom/IntersectionObserver.cpp
index c784a1c..14f97d8 100644
--- a/third_party/WebKit/Source/core/dom/IntersectionObserver.cpp
+++ b/third_party/WebKit/Source/core/dom/IntersectionObserver.cpp
@@ -196,7 +196,7 @@
 
 void IntersectionObserver::computeIntersectionObservations()
 {
-    if (!m_root || !m_root->inDocument())
+    if (!m_root || !m_root->inShadowIncludingDocument())
         return;
     Document* callbackDocument = toDocument(m_callback->getExecutionContext());
     if (!callbackDocument)
diff --git a/third_party/WebKit/Source/core/dom/LayoutTreeBuilderTraversal.cpp b/third_party/WebKit/Source/core/dom/LayoutTreeBuilderTraversal.cpp
index f5d97695..6da9198 100644
--- a/third_party/WebKit/Source/core/dom/LayoutTreeBuilderTraversal.cpp
+++ b/third_party/WebKit/Source/core/dom/LayoutTreeBuilderTraversal.cpp
@@ -54,7 +54,7 @@
 ContainerNode* parent(const Node& node, ParentDetails* details)
 {
     // TODO(hayato): Uncomment this once we can be sure LayoutTreeBuilderTraversal::parent() is used only for a node in a document.
-    // ASSERT(node.inDocument());
+    // ASSERT(node.inShadowIncludingDocument());
     return FlatTreeTraversal::parent(node, details);
 }
 
diff --git a/third_party/WebKit/Source/core/dom/Node.cpp b/third_party/WebKit/Source/core/dom/Node.cpp
index cfabb0f..cdcbf0a9 100644
--- a/third_party/WebKit/Source/core/dom/Node.cpp
+++ b/third_party/WebKit/Source/core/dom/Node.cpp
@@ -616,11 +616,11 @@
 }
 #endif
 
-inline static Node& rootInComposedTree(const Node& node)
+Node& Node::shadowIncludingRoot() const
 {
-    if (node.inDocument())
-        return node.document();
-    Node* root = const_cast<Node*>(&node);
+    if (inShadowIncludingDocument())
+        return document();
+    Node* root = const_cast<Node*>(this);
     while (Node* host = root->shadowHost())
         root = host;
     while (Node* ancestor = root->parentNode())
@@ -632,18 +632,18 @@
 #if ENABLE(ASSERT)
 bool Node::needsDistributionRecalc() const
 {
-    return rootInComposedTree(*this).childNeedsDistributionRecalc();
+    return shadowIncludingRoot().childNeedsDistributionRecalc();
 }
 #endif
 
 void Node::updateDistribution()
 {
     // Extra early out to avoid spamming traces.
-    if (inDocument() && !document().childNeedsDistributionRecalc())
+    if (inShadowIncludingDocument() && !document().childNeedsDistributionRecalc())
         return;
     TRACE_EVENT0("blink", "Node::updateDistribution");
     ScriptForbiddenScope forbidScript;
-    Node& root = rootInComposedTree(*this);
+    Node& root = shadowIncludingRoot();
     if (root.childNeedsDistributionRecalc())
         root.recalcDistribution();
 }
@@ -694,7 +694,7 @@
 void Node::markAncestorsWithChildNeedsDistributionRecalc()
 {
     ScriptForbiddenScope forbidScriptDuringRawIteration;
-    if (RuntimeEnabledFeatures::shadowDOMV1Enabled() && inDocument() && !document().childNeedsDistributionRecalc()) {
+    if (RuntimeEnabledFeatures::shadowDOMV1Enabled() && inShadowIncludingDocument() && !document().childNeedsDistributionRecalc()) {
         // TODO(hayato): Support a non-document composed tree.
         // TODO(hayato): Enqueue a task only if a 'slotchange' event listner is registered in the document composed tree.
         Microtask::enqueueMicrotask(WTF::bind(&Document::updateDistribution, RawPtr<Document>(&document())));
@@ -752,7 +752,7 @@
 
 bool Node::inActiveDocument() const
 {
-    return inDocument() && document().isActive();
+    return inShadowIncludingDocument() && document().isActive();
 }
 
 Node* Node::focusDelegate()
@@ -796,7 +796,7 @@
 bool Node::isDescendantOf(const Node *other) const
 {
     // Return true if other is an ancestor of this, otherwise false
-    if (!other || !other->hasChildren() || inDocument() != other->inDocument())
+    if (!other || !other->hasChildren() || inShadowIncludingDocument() != other->inShadowIncludingDocument())
         return false;
     if (other->treeScope() != treeScope())
         return false;
@@ -816,7 +816,7 @@
     return this == node || node->isDescendantOf(this);
 }
 
-bool Node::containsIncludingShadowDOM(const Node* node) const
+bool Node::isShadowIncludingInclusiveAncestorOf(const Node* node) const
 {
     if (!node)
         return false;
@@ -827,7 +827,7 @@
     if (document() != node->document())
         return false;
 
-    if (inDocument() != node->inDocument())
+    if (inShadowIncludingDocument() != node->inShadowIncludingDocument())
         return false;
 
     bool hasChildren = isContainerNode() && toContainerNode(this)->hasChildren();
@@ -1416,8 +1416,8 @@
 
     // If one node is in the document and the other is not, we must be disconnected.
     // If the nodes have different owning documents, they must be disconnected.  Note that we avoid
-    // comparing Attr nodes here, since they return false from inDocument() all the time (which seems like a bug).
-    if (start1->inDocument() != start2->inDocument() || (treatment == TreatShadowTreesAsDisconnected && start1->treeScope() != start2->treeScope())) {
+    // comparing Attr nodes here, since they return false from inShadowIncludingDocument() all the time (which seems like a bug).
+    if (start1->inShadowIncludingDocument() != start2->inShadowIncludingDocument() || (treatment == TreatShadowTreesAsDisconnected && start1->treeScope() != start2->treeScope())) {
         unsigned short direction = (this > otherNode) ? DOCUMENT_POSITION_PRECEDING : DOCUMENT_POSITION_FOLLOWING;
         return DOCUMENT_POSITION_DISCONNECTED | DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | direction;
     }
diff --git a/third_party/WebKit/Source/core/dom/Node.h b/third_party/WebKit/Source/core/dom/Node.h
index a2922b8d..6e3f3b2 100644
--- a/third_party/WebKit/Source/core/dom/Node.h
+++ b/third_party/WebKit/Source/core/dom/Node.h
@@ -214,6 +214,7 @@
     Node* firstChild() const;
     Node* lastChild() const;
     Node& treeRoot() const;
+    Node& shadowIncludingRoot() const;
 
     void remove(ExceptionState& = ASSERT_NO_EXCEPTION);
 
@@ -475,9 +476,9 @@
 
     bool inActiveDocument() const;
 
-    // Returns true if this node is associated with a document and is in its associated document's
+    // Returns true if this node is associated with a shadow-including document and is in its associated document's
     // node tree, false otherwise.
-    bool inDocument() const
+    bool inShadowIncludingDocument() const
     {
         return getFlag(InDocumentFlag);
     }
@@ -497,7 +498,7 @@
 
     bool isDescendantOf(const Node*) const;
     bool contains(const Node*) const;
-    bool containsIncludingShadowDOM(const Node*) const;
+    bool isShadowIncludingInclusiveAncestorOf(const Node*) const;
     bool containsIncludingHostElements(const Node&) const;
     Node* commonAncestor(const Node&, ContainerNode* (*parent)(const Node&)) const;
 
@@ -570,7 +571,7 @@
     // dispatching.
     //
     // WebKit notifies this callback regardless if the subtree of the node is a document tree or a floating subtree.
-    // Implementation can determine the type of subtree by seeing insertionPoint->inDocument().
+    // Implementation can determine the type of subtree by seeing insertionPoint->inShadowIncludingDocument().
     // For a performance reason, notifications are delivered only to ContainerNode subclasses if the insertionPoint is out of document.
     //
     // There are another callback named didNotifySubtreeInsertionsToDocument(), which is called after all the descendant is notified,
diff --git a/third_party/WebKit/Source/core/dom/NodeChildRemovalTracker.h b/third_party/WebKit/Source/core/dom/NodeChildRemovalTracker.h
index 8f696b9..b3857b6 100644
--- a/third_party/WebKit/Source/core/dom/NodeChildRemovalTracker.h
+++ b/third_party/WebKit/Source/core/dom/NodeChildRemovalTracker.h
@@ -66,7 +66,7 @@
 inline bool NodeChildRemovalTracker::isBeingRemoved(Node* node)
 {
     for (NodeChildRemovalTracker* removal = s_last; removal; removal = removal->previous()) {
-        if (removal->node().containsIncludingShadowDOM(node))
+        if (removal->node().isShadowIncludingInclusiveAncestorOf(node))
             return true;
     }
 
diff --git a/third_party/WebKit/Source/core/dom/PresentationAttributeStyle.cpp b/third_party/WebKit/Source/core/dom/PresentationAttributeStyle.cpp
index 9ba0943..f24c32f 100644
--- a/third_party/WebKit/Source/core/dom/PresentationAttributeStyle.cpp
+++ b/third_party/WebKit/Source/core/dom/PresentationAttributeStyle.cpp
@@ -173,7 +173,7 @@
         cacheValue = nullptr;
     }
 
-    RawPtr<StylePropertySet> style = nullptr;
+    StylePropertySet* style = nullptr;
     if (cacheHash && cacheValue->value) {
         style = cacheValue->value->value;
         cacheCleaner.didHitPresentationAttributeCache();
@@ -185,7 +185,7 @@
     }
 
     if (!cacheHash || cacheValue->value)
-        return style.release();
+        return style;
 
     RawPtr<PresentationAttributeCacheEntry> newEntry = new PresentationAttributeCacheEntry;
     newEntry->key = cacheKey;
@@ -201,7 +201,7 @@
         cacheValue->value = newEntry.release();
     }
 
-    return style.release();
+    return style;
 }
 
 } // namespace blink
diff --git a/third_party/WebKit/Source/core/dom/ProcessingInstruction.cpp b/third_party/WebKit/Source/core/dom/ProcessingInstruction.cpp
index c7519c83..86abb2d 100644
--- a/third_party/WebKit/Source/core/dom/ProcessingInstruction.cpp
+++ b/third_party/WebKit/Source/core/dom/ProcessingInstruction.cpp
@@ -60,9 +60,9 @@
         clearSheet();
 
     // FIXME: ProcessingInstruction should not be in document here.
-    // However, if we add ASSERT(!inDocument()), fast/xsl/xslt-entity.xml
+    // However, if we add ASSERT(!inShadowIncludingDocument()), fast/xsl/xslt-entity.xml
     // crashes. We need to investigate ProcessingInstruction lifetime.
-    if (inDocument() && m_isCSS)
+    if (inShadowIncludingDocument() && m_isCSS)
         document().styleEngine().removeStyleSheetCandidateNode(this);
     clearEventListenerForXSLT();
 #endif
@@ -203,7 +203,7 @@
 
 void ProcessingInstruction::setCSSStyleSheet(const String& href, const KURL& baseURL, const String& charset, const CSSStyleSheetResource* sheet)
 {
-    if (!inDocument()) {
+    if (!inShadowIncludingDocument()) {
         ASSERT(!m_sheet);
         return;
     }
@@ -228,7 +228,7 @@
 
 void ProcessingInstruction::setXSLStyleSheet(const String& href, const KURL& baseURL, const String& sheet)
 {
-    if (!inDocument()) {
+    if (!inShadowIncludingDocument()) {
         ASSERT(!m_sheet);
         return;
     }
@@ -259,7 +259,7 @@
 Node::InsertionNotificationRequest ProcessingInstruction::insertedInto(ContainerNode* insertionPoint)
 {
     CharacterData::insertedInto(insertionPoint);
-    if (!insertionPoint->inDocument())
+    if (!insertionPoint->inShadowIncludingDocument())
         return InsertionDone;
 
     String href;
@@ -275,7 +275,7 @@
 void ProcessingInstruction::removedFrom(ContainerNode* insertionPoint)
 {
     CharacterData::removedFrom(insertionPoint);
-    if (!insertionPoint->inDocument())
+    if (!insertionPoint->inShadowIncludingDocument())
         return;
 
     // No need to remove XSLStyleSheet from StyleEngine.
diff --git a/third_party/WebKit/Source/core/dom/Range.cpp b/third_party/WebKit/Source/core/dom/Range.cpp
index 8fa8dca5..242765cb 100644
--- a/third_party/WebKit/Source/core/dom/Range.cpp
+++ b/third_party/WebKit/Source/core/dom/Range.cpp
@@ -117,10 +117,10 @@
 #endif
 }
 
-bool Range::inDocument() const
+bool Range::inShadowIncludingDocument() const
 {
-    ASSERT(m_start.inDocument() == m_end.inDocument());
-    return m_start.inDocument();
+    ASSERT(m_start.inShadowIncludingDocument() == m_end.inShadowIncludingDocument());
+    return m_start.inShadowIncludingDocument();
 }
 
 void Range::setDocument(Document& document)
@@ -1186,7 +1186,7 @@
         return;
     }
 
-    if (newParent->containsIncludingShadowDOM(m_start.container())) {
+    if (newParent->isShadowIncludingInclusiveAncestorOf(m_start.container())) {
         exceptionState.throwDOMException(HierarchyRequestError, "The node provided contains the insertion point; it may not be inserted into itself.");
         return;
     }
diff --git a/third_party/WebKit/Source/core/dom/Range.h b/third_party/WebKit/Source/core/dom/Range.h
index 9619fff..87059355 100644
--- a/third_party/WebKit/Source/core/dom/Range.h
+++ b/third_party/WebKit/Source/core/dom/Range.h
@@ -65,7 +65,7 @@
     int endOffset() const { return m_end.offset(); }
 
     bool collapsed() const { return m_start == m_end; }
-    bool inDocument() const;
+    bool inShadowIncludingDocument() const;
 
     Node* commonAncestorContainer() const;
     static Node* commonAncestorContainer(const Node* containerA, const Node* containerB);
diff --git a/third_party/WebKit/Source/core/dom/RangeBoundaryPoint.h b/third_party/WebKit/Source/core/dom/RangeBoundaryPoint.h
index 85ad5695..11c78126 100644
--- a/third_party/WebKit/Source/core/dom/RangeBoundaryPoint.h
+++ b/third_party/WebKit/Source/core/dom/RangeBoundaryPoint.h
@@ -39,7 +39,7 @@
 
     explicit RangeBoundaryPoint(const RangeBoundaryPoint&);
 
-    bool inDocument() const;
+    bool inShadowIncludingDocument() const;
     const Position toPosition() const;
 
     Node* container() const;
@@ -107,9 +107,9 @@
     m_offsetInContainer = m_childBeforeBoundary->nodeIndex() + 1;
 }
 
-inline bool RangeBoundaryPoint::inDocument() const
+inline bool RangeBoundaryPoint::inShadowIncludingDocument() const
 {
-    return m_containerNode && m_containerNode->inDocument();
+    return m_containerNode && m_containerNode->inShadowIncludingDocument();
 }
 
 inline const Position RangeBoundaryPoint::toPosition() const
diff --git a/third_party/WebKit/Source/core/dom/ScriptLoader.cpp b/third_party/WebKit/Source/core/dom/ScriptLoader.cpp
index ac746c5..c2762f5 100644
--- a/third_party/WebKit/Source/core/dom/ScriptLoader.cpp
+++ b/third_party/WebKit/Source/core/dom/ScriptLoader.cpp
@@ -95,7 +95,7 @@
 
 void ScriptLoader::childrenChanged()
 {
-    if (!m_parserInserted && m_element->inDocument())
+    if (!m_parserInserted && m_element->inShadowIncludingDocument())
         prepareScript(); // FIXME: Provide a real starting line number here.
 }
 
@@ -208,7 +208,7 @@
     if (!client->hasSourceAttribute() && !m_element->hasChildren())
         return false;
 
-    if (!m_element->inDocument())
+    if (!m_element->inShadowIncludingDocument())
         return false;
 
     if (!isScriptTypeSupported(supportLegacyTypes))
@@ -287,7 +287,7 @@
     ASSERT(m_element);
 
     RawPtr<Document> elementDocument(m_element->document());
-    if (!m_element->inDocument() || m_element->document() != elementDocument)
+    if (!m_element->inShadowIncludingDocument() || m_element->document() != elementDocument)
         return false;
 
     ASSERT(!m_resource);
@@ -484,7 +484,7 @@
 
 bool ScriptLoader::ignoresLoadRequest() const
 {
-    return m_alreadyStarted || m_isExternalScript || m_parserInserted || !element() || !element()->inDocument();
+    return m_alreadyStarted || m_isExternalScript || m_parserInserted || !element() || !element()->inShadowIncludingDocument();
 }
 
 bool ScriptLoader::isScriptForEventSupported() const
diff --git a/third_party/WebKit/Source/core/dom/SelectorQuery.cpp b/third_party/WebKit/Source/core/dom/SelectorQuery.cpp
index ee5af5b..7f6f4c1 100644
--- a/third_party/WebKit/Source/core/dom/SelectorQuery.cpp
+++ b/third_party/WebKit/Source/core/dom/SelectorQuery.cpp
@@ -225,7 +225,7 @@
         return false;
     if (rootNode.document().inQuirksMode())
         return false;
-    if (!rootNode.inDocument())
+    if (!rootNode.inShadowIncludingDocument())
         return false;
     return m_selectors.size() == 1;
 }
diff --git a/third_party/WebKit/Source/core/dom/StyleElement.cpp b/third_party/WebKit/Source/core/dom/StyleElement.cpp
index dfc733e..b96cea5 100644
--- a/third_party/WebKit/Source/core/dom/StyleElement.cpp
+++ b/third_party/WebKit/Source/core/dom/StyleElement.cpp
@@ -65,7 +65,7 @@
 {
     TRACE_EVENT0("blink", "StyleElement::processStyleSheet");
     ASSERT(element);
-    ASSERT(element->inDocument());
+    ASSERT(element->inShadowIncludingDocument());
 
     m_registeredAsCandidate = true;
     document.styleEngine().addStyleSheetCandidateNode(element);
@@ -77,7 +77,7 @@
 
 void StyleElement::insertedInto(Element* element, ContainerNode* insertionPoint)
 {
-    if (!insertionPoint->inDocument() || !element->isInShadowTree())
+    if (!insertionPoint->inShadowIncludingDocument() || !element->isInShadowTree())
         return;
     if (ShadowRoot* scope = element->containingShadowRoot())
         scope->registerScopedHTMLStyleChild();
@@ -85,7 +85,7 @@
 
 void StyleElement::removedFrom(Element* element, ContainerNode* insertionPoint)
 {
-    if (!insertionPoint->inDocument())
+    if (!insertionPoint->inShadowIncludingDocument())
         return;
 
     ShadowRoot* shadowRoot = element->containingShadowRoot();
@@ -115,7 +115,7 @@
         m_sheet->clearOwnerNode();
 
     if (m_registeredAsCandidate) {
-        ASSERT(element->inDocument());
+        ASSERT(element->inShadowIncludingDocument());
         document.styleEngine().removeStyleSheetCandidateNode(element, element->treeScope());
         m_registeredAsCandidate = false;
     }
@@ -140,7 +140,7 @@
 
 StyleElement::ProcessingResult StyleElement::process(Element* element)
 {
-    if (!element || !element->inDocument())
+    if (!element || !element->inShadowIncludingDocument())
         return ProcessingSuccessful;
     return createSheet(element, element->textFromChildren());
 }
@@ -173,7 +173,7 @@
 StyleElement::ProcessingResult StyleElement::createSheet(Element* e, const String& text)
 {
     ASSERT(e);
-    ASSERT(e->inDocument());
+    ASSERT(e->inShadowIncludingDocument());
     Document& document = e->document();
 
     const ContentSecurityPolicy* csp = document.contentSecurityPolicy();
diff --git a/third_party/WebKit/Source/core/dom/StyleEngine.cpp b/third_party/WebKit/Source/core/dom/StyleEngine.cpp
index 9938cdf..98c81eb5 100644
--- a/third_party/WebKit/Source/core/dom/StyleEngine.cpp
+++ b/third_party/WebKit/Source/core/dom/StyleEngine.cpp
@@ -164,7 +164,7 @@
 {
     ASSERT(styleSheetCandidateNode);
     TreeScope* treeScope = isStyleElement(*styleSheetCandidateNode) ? &styleSheetCandidateNode->treeScope() : m_document.get();
-    if (styleSheetCandidateNode->inDocument())
+    if (styleSheetCandidateNode->inShadowIncludingDocument())
         markTreeScopeDirty(*treeScope);
 
     // Make sure we knew this sheet was pending, and that our count isn't out of sync.
@@ -188,7 +188,7 @@
 
     if (sheet && document().isActive()) {
         Node* node = sheet->ownerNode();
-        if (node && node->inDocument()) {
+        if (node && node->inShadowIncludingDocument()) {
             TreeScope& treeScope = isStyleElement(*node) ? node->treeScope() : *m_document;
             ASSERT(isStyleElement(*node) || node->treeScope() == m_document);
             markTreeScopeDirty(treeScope);
@@ -200,7 +200,7 @@
 
 void StyleEngine::addStyleSheetCandidateNode(Node* node)
 {
-    if (!node->inDocument() || document().isDetached())
+    if (!node->inShadowIncludingDocument() || document().isDetached())
         return;
 
     TreeScope& treeScope = isStyleElement(*node) ? node->treeScope() : *m_document;
@@ -237,7 +237,7 @@
 
 void StyleEngine::modifiedStyleSheetCandidateNode(Node* node)
 {
-    if (!node->inDocument())
+    if (!node->inShadowIncludingDocument())
         return;
 
     TreeScope& treeScope = isStyleElement(*node) ? node->treeScope() : *m_document;
diff --git a/third_party/WebKit/Source/core/dom/TreeScopeStyleSheetCollection.cpp b/third_party/WebKit/Source/core/dom/TreeScopeStyleSheetCollection.cpp
index 4e2577d..2c8a034 100644
--- a/third_party/WebKit/Source/core/dom/TreeScopeStyleSheetCollection.cpp
+++ b/third_party/WebKit/Source/core/dom/TreeScopeStyleSheetCollection.cpp
@@ -46,7 +46,7 @@
 
 void TreeScopeStyleSheetCollection::addStyleSheetCandidateNode(Node* node)
 {
-    if (!node->inDocument())
+    if (!node->inShadowIncludingDocument())
         return;
 
     m_styleSheetCandidateNodes.add(node);
diff --git a/third_party/WebKit/Source/core/dom/custom/CustomElementCallbackInvocation.cpp b/third_party/WebKit/Source/core/dom/custom/CustomElementCallbackInvocation.cpp
index 1a1c7afc..cb1256623 100644
--- a/third_party/WebKit/Source/core/dom/custom/CustomElementCallbackInvocation.cpp
+++ b/third_party/WebKit/Source/core/dom/custom/CustomElementCallbackInvocation.cpp
@@ -106,7 +106,7 @@
 
 void CreatedInvocation::dispatch(Element* element)
 {
-    if (element->inDocument() && element->document().domWindow())
+    if (element->inShadowIncludingDocument() && element->document().domWindow())
         CustomElementScheduler::scheduleCallback(callbacks(), element, CustomElementLifecycleCallbacks::AttachedCallback);
     callbacks()->created(element);
 }
diff --git a/third_party/WebKit/Source/core/dom/shadow/FlatTreeTraversal.cpp b/third_party/WebKit/Source/core/dom/shadow/FlatTreeTraversal.cpp
index a37c9976..7ffe495c 100644
--- a/third_party/WebKit/Source/core/dom/shadow/FlatTreeTraversal.cpp
+++ b/third_party/WebKit/Source/core/dom/shadow/FlatTreeTraversal.cpp
@@ -279,7 +279,7 @@
 {
     assertPrecondition(node);
     assertPrecondition(other);
-    if (!hasChildren(other) || node.inDocument() != other.inDocument())
+    if (!hasChildren(other) || node.inShadowIncludingDocument() != other.inShadowIncludingDocument())
         return false;
     for (const ContainerNode* n = traverseParent(node); n; n = traverseParent(*n)) {
         if (n == other)
diff --git a/third_party/WebKit/Source/core/dom/shadow/ShadowRoot.cpp b/third_party/WebKit/Source/core/dom/shadow/ShadowRoot.cpp
index 23da88b7..0edd044 100644
--- a/third_party/WebKit/Source/core/dom/shadow/ShadowRoot.cpp
+++ b/third_party/WebKit/Source/core/dom/shadow/ShadowRoot.cpp
@@ -160,7 +160,7 @@
 {
     DocumentFragment::insertedInto(insertionPoint);
 
-    if (!insertionPoint->inDocument() || !isOldest())
+    if (!insertionPoint->inShadowIncludingDocument() || !isOldest())
         return InsertionDone;
 
     // FIXME: When parsing <video controls>, insertedInto() is called many times without invoking removedFrom.
@@ -179,7 +179,7 @@
 
 void ShadowRoot::removedFrom(ContainerNode* insertionPoint)
 {
-    if (insertionPoint->inDocument()) {
+    if (insertionPoint->inShadowIncludingDocument()) {
         document().styleEngine().shadowRootRemovedFromDocument(this);
         if (m_registeredWithParentShadowRoot) {
             ShadowRoot* root = host()->containingShadowRoot();
diff --git a/third_party/WebKit/Source/core/editing/DOMSelection.cpp b/third_party/WebKit/Source/core/editing/DOMSelection.cpp
index 27cd215..69c0d67 100644
--- a/third_party/WebKit/Source/core/editing/DOMSelection.cpp
+++ b/third_party/WebKit/Source/core/editing/DOMSelection.cpp
@@ -402,7 +402,7 @@
     if (!m_frame)
         return;
 
-    if (!newRange->inDocument()) {
+    if (!newRange->inShadowIncludingDocument()) {
         addConsoleError("The given range isn't in document.");
         return;
     }
diff --git a/third_party/WebKit/Source/core/editing/DragCaretController.cpp b/third_party/WebKit/Source/core/editing/DragCaretController.cpp
index 6a50958..fe77956 100644
--- a/third_party/WebKit/Source/core/editing/DragCaretController.cpp
+++ b/third_party/WebKit/Source/core/editing/DragCaretController.cpp
@@ -81,7 +81,7 @@
         return false;
 
     Element& element = toElement(node);
-    return element.containsIncludingShadowDOM(position.anchorNode());
+    return element.isShadowIncludingInclusiveAncestorOf(position.anchorNode());
 }
 
 void DragCaretController::nodeWillBeRemoved(Node& node)
diff --git a/third_party/WebKit/Source/core/editing/EditingStyle.cpp b/third_party/WebKit/Source/core/editing/EditingStyle.cpp
index b189ce9..3a081a48 100644
--- a/third_party/WebKit/Source/core/editing/EditingStyle.cpp
+++ b/third_party/WebKit/Source/core/editing/EditingStyle.cpp
@@ -140,7 +140,7 @@
     return allEditingProperties().contains(static_cast<CSSPropertyID>(id));
 }
 
-static RawPtr<MutableStylePropertySet> editingStyleFromComputedStyle(RawPtr<CSSComputedStyleDeclaration> style, EditingPropertiesType type = OnlyInheritableEditingProperties)
+static MutableStylePropertySet* editingStyleFromComputedStyle(RawPtr<CSSComputedStyleDeclaration> style, EditingPropertiesType type = OnlyInheritableEditingProperties)
 {
     if (!style)
         return MutableStylePropertySet::create(HTMLQuirksMode);
@@ -293,8 +293,8 @@
 
 bool HTMLAttributeEquivalent::valueIsPresentInStyle(HTMLElement* element, StylePropertySet* style) const
 {
-    RawPtr<CSSValue> value = attributeValueAsCSSValue(element);
-    RawPtr<CSSValue> styleValue = style->getPropertyCSSValue(m_propertyID);
+    CSSValue* value = attributeValueAsCSSValue(element);
+    CSSValue* styleValue = style->getPropertyCSSValue(m_propertyID);
 
     return compareCSSValuePtr(value, styleValue);
 }
@@ -407,27 +407,27 @@
 
 static inline Color getFontColor(CSSStyleDeclaration* style)
 {
-    return cssValueToColor(style->getPropertyCSSValueInternal(CSSPropertyColor).get());
+    return cssValueToColor(style->getPropertyCSSValueInternal(CSSPropertyColor));
 }
 
 static inline Color getFontColor(StylePropertySet* style)
 {
-    return cssValueToColor(style->getPropertyCSSValue(CSSPropertyColor).get());
+    return cssValueToColor(style->getPropertyCSSValue(CSSPropertyColor));
 }
 
 static inline Color getBackgroundColor(CSSStyleDeclaration* style)
 {
-    return cssValueToColor(style->getPropertyCSSValueInternal(CSSPropertyBackgroundColor).get());
+    return cssValueToColor(style->getPropertyCSSValueInternal(CSSPropertyBackgroundColor));
 }
 
 static inline Color getBackgroundColor(StylePropertySet* style)
 {
-    return cssValueToColor(style->getPropertyCSSValue(CSSPropertyBackgroundColor).get());
+    return cssValueToColor(style->getPropertyCSSValue(CSSPropertyBackgroundColor));
 }
 
 static inline Color backgroundColorInEffect(Node* node)
 {
-    return cssValueToColor(backgroundColorValueInEffect(node).get());
+    return cssValueToColor(backgroundColorValueInEffect(node));
 }
 
 static int textAlignResolvingStartAndEnd(int textAlign, int direction)
@@ -928,7 +928,7 @@
 
 bool EditingStyle::styleIsPresentInComputedStyleOfNode(Node* node) const
 {
-    return !m_mutableStyle || getPropertiesNotIn(m_mutableStyle.get(), CSSComputedStyleDeclaration::create(node).get())->isEmpty();
+    return !m_mutableStyle || getPropertiesNotIn(m_mutableStyle.get(), CSSComputedStyleDeclaration::create(node))->isEmpty();
 }
 
 bool EditingStyle::elementIsStyledSpanOrHTMLEquivalent(const HTMLElement* element)
@@ -992,8 +992,8 @@
     RawPtr<EditingStyle> editingStyleAtPosition = EditingStyle::create(position, EditingPropertiesInEffect);
     StylePropertySet* styleAtPosition = editingStyleAtPosition->m_mutableStyle.get();
 
-    RawPtr<CSSValue> unicodeBidi = nullptr;
-    RawPtr<CSSValue> direction = nullptr;
+    CSSValue* unicodeBidi = nullptr;
+    CSSValue* direction = nullptr;
     if (shouldPreserveWritingDirection == PreserveWritingDirection) {
         unicodeBidi = m_mutableStyle->getPropertyCSSValue(CSSPropertyUnicodeBidi);
         direction = m_mutableStyle->getPropertyCSSValue(CSSPropertyDirection);
@@ -1008,13 +1008,13 @@
         m_mutableStyle->removeProperty(CSSPropertyColor);
 
     if (hasTransparentBackgroundColor(m_mutableStyle.get())
-        || cssValueToColor(m_mutableStyle->getPropertyCSSValue(CSSPropertyBackgroundColor).get()) == backgroundColorInEffect(position.computeContainerNode()))
+        || cssValueToColor(m_mutableStyle->getPropertyCSSValue(CSSPropertyBackgroundColor)) == backgroundColorInEffect(position.computeContainerNode()))
         m_mutableStyle->removeProperty(CSSPropertyBackgroundColor);
 
     if (unicodeBidi && unicodeBidi->isPrimitiveValue()) {
-        m_mutableStyle->setProperty(CSSPropertyUnicodeBidi, toCSSPrimitiveValue(unicodeBidi.get())->getValueID());
+        m_mutableStyle->setProperty(CSSPropertyUnicodeBidi, toCSSPrimitiveValue(unicodeBidi)->getValueID());
         if (direction && direction->isPrimitiveValue())
-            m_mutableStyle->setProperty(CSSPropertyDirection, toCSSPrimitiveValue(direction.get())->getValueID());
+            m_mutableStyle->setProperty(CSSPropertyDirection, toCSSPrimitiveValue(direction)->getValueID());
     }
 }
 
diff --git a/third_party/WebKit/Source/core/editing/EditingUtilities.cpp b/third_party/WebKit/Source/core/editing/EditingUtilities.cpp
index 3fb0b51..8afb247a 100644
--- a/third_party/WebKit/Source/core/editing/EditingUtilities.cpp
+++ b/third_party/WebKit/Source/core/editing/EditingUtilities.cpp
@@ -1447,25 +1447,25 @@
         return;
     switch (position.anchorType()) {
     case PositionAnchorType::BeforeChildren:
-        if (node.containsIncludingShadowDOM(position.computeContainerNode()))
+        if (node.isShadowIncludingInclusiveAncestorOf(position.computeContainerNode()))
             position = positionInParentBeforeNode(node);
         break;
     case PositionAnchorType::AfterChildren:
-        if (node.containsIncludingShadowDOM(position.computeContainerNode()))
+        if (node.isShadowIncludingInclusiveAncestorOf(position.computeContainerNode()))
             position = positionInParentAfterNode(node);
         break;
     case PositionAnchorType::OffsetInAnchor:
         if (position.computeContainerNode() == node.parentNode() && static_cast<unsigned>(position.offsetInContainerNode()) > node.nodeIndex())
             position = Position(position.computeContainerNode(), position.offsetInContainerNode() - 1);
-        else if (node.containsIncludingShadowDOM(position.computeContainerNode()))
+        else if (node.isShadowIncludingInclusiveAncestorOf(position.computeContainerNode()))
             position = positionInParentBeforeNode(node);
         break;
     case PositionAnchorType::AfterAnchor:
-        if (node.containsIncludingShadowDOM(position.anchorNode()))
+        if (node.isShadowIncludingInclusiveAncestorOf(position.anchorNode()))
             position = positionInParentAfterNode(node);
         break;
     case PositionAnchorType::BeforeAnchor:
-        if (node.containsIncludingShadowDOM(position.anchorNode()))
+        if (node.isShadowIncludingInclusiveAncestorOf(position.anchorNode()))
             position = positionInParentBeforeNode(node);
         break;
     }
diff --git a/third_party/WebKit/Source/core/editing/EphemeralRange.cpp b/third_party/WebKit/Source/core/editing/EphemeralRange.cpp
index e82f556..e41b16f7 100644
--- a/third_party/WebKit/Source/core/editing/EphemeralRange.cpp
+++ b/third_party/WebKit/Source/core/editing/EphemeralRange.cpp
@@ -25,8 +25,8 @@
     }
     ASSERT(m_endPosition.isNotNull());
     ASSERT(m_startPosition.document() == m_endPosition.document());
-    ASSERT(m_startPosition.inDocument());
-    ASSERT(m_endPosition.inDocument());
+    ASSERT(m_startPosition.inShadowIncludingDocument());
+    ASSERT(m_endPosition.inShadowIncludingDocument());
 }
 
 template <typename Strategy>
@@ -47,7 +47,7 @@
 {
     if (!range)
         return;
-    ASSERT(range->inDocument());
+    ASSERT(range->inShadowIncludingDocument());
     m_startPosition = fromPositionInDOMTree<Strategy>(range->startPosition());
     m_endPosition = fromPositionInDOMTree<Strategy>(range->endPosition());
 #if ENABLE(ASSERT)
diff --git a/third_party/WebKit/Source/core/editing/FrameSelection.cpp b/third_party/WebKit/Source/core/editing/FrameSelection.cpp
index a47d7c5..e26488e 100644
--- a/third_party/WebKit/Source/core/editing/FrameSelection.cpp
+++ b/third_party/WebKit/Source/core/editing/FrameSelection.cpp
@@ -395,7 +395,7 @@
         return false;
 
     Element& element = toElement(node);
-    return element.containsIncludingShadowDOM(position.anchorNode());
+    return element.isShadowIncludingInclusiveAncestorOf(position.anchorNode());
 }
 
 void FrameSelection::nodeWillBeRemoved(Node& node)
@@ -515,7 +515,7 @@
 void FrameSelection::didUpdateCharacterData(CharacterData* node, unsigned offset, unsigned oldLength, unsigned newLength)
 {
     // The fragment check is a performance optimization. See http://trac.webkit.org/changeset/30062.
-    if (isNone() || !node || !node->inDocument())
+    if (isNone() || !node || !node->inShadowIncludingDocument())
         return;
 
     Position base = updatePositionAfterAdoptingTextReplacement(selection().base(), node, offset, oldLength, newLength);
@@ -544,7 +544,7 @@
 
 void FrameSelection::didMergeTextNodes(const Text& oldNode, unsigned offset)
 {
-    if (isNone() || !oldNode.inDocument())
+    if (isNone() || !oldNode.inShadowIncludingDocument())
         return;
     Position base = updatePostionAfterAdoptingTextNodesMerged(selection().base(), oldNode, offset);
     Position extent = updatePostionAfterAdoptingTextNodesMerged(selection().extent(), oldNode, offset);
@@ -568,7 +568,7 @@
 
 void FrameSelection::didSplitTextNode(const Text& oldNode)
 {
-    if (isNone() || !oldNode.inDocument())
+    if (isNone() || !oldNode.inShadowIncludingDocument())
         return;
     Position base = updatePostionAfterAdoptingTextNodeSplit(selection().base(), oldNode);
     Position extent = updatePostionAfterAdoptingTextNodeSplit(selection().extent(), oldNode);
@@ -864,7 +864,7 @@
         if (selectStartTarget->dispatchEvent(Event::createCancelableBubble(EventTypeNames::selectstart)) != DispatchEventResult::NotCanceled)
             return;
         // |root| may be detached due to selectstart event.
-        if (!root->inDocument() || root->document() != document)
+        if (!root->inShadowIncludingDocument() || root->document() != document)
             return;
     }
 
@@ -876,7 +876,7 @@
 
 bool FrameSelection::setSelectedRange(Range* range, TextAffinity affinity, SelectionDirectionalMode directional, SetSelectionOptions options)
 {
-    if (!range || !range->inDocument())
+    if (!range || !range->inShadowIncludingDocument())
         return false;
     ASSERT(range->startContainer()->document() == range->endContainer()->document());
     return setSelectedRange(EphemeralRange(range), affinity, directional, options);
@@ -1055,7 +1055,7 @@
     if (!focusedElement)
         return false;
 
-    return focusedElement->containsIncludingShadowDOM(selection().start().anchorNode());
+    return focusedElement->isShadowIncludingInclusiveAncestorOf(selection().start().anchorNode());
 }
 
 void FrameSelection::caretBlinkTimerFired(Timer<FrameSelection>*)
diff --git a/third_party/WebKit/Source/core/editing/PendingSelection.cpp b/third_party/WebKit/Source/core/editing/PendingSelection.cpp
index 7e28d9f..02afe9e 100644
--- a/third_party/WebKit/Source/core/editing/PendingSelection.cpp
+++ b/third_party/WebKit/Source/core/editing/PendingSelection.cpp
@@ -44,13 +44,13 @@
 static bool isSelectionInDocument(const VisibleSelectionInFlatTree& visibleSelection, const Document& document)
 {
     const PositionInFlatTree& start = visibleSelection.start();
-    if (start.isNotNull() && (!start.inDocument() || start.document() != document))
+    if (start.isNotNull() && (!start.inShadowIncludingDocument() || start.document() != document))
         return false;
     const PositionInFlatTree& end = visibleSelection.end();
-    if (end.isNotNull() && (!end.inDocument() || end.document() != document))
+    if (end.isNotNull() && (!end.inShadowIncludingDocument() || end.document() != document))
         return false;
     const PositionInFlatTree extent = visibleSelection.extent();
-    if (extent.isNotNull() && (!extent.inDocument() || extent.document() != document))
+    if (extent.isNotNull() && (!extent.inShadowIncludingDocument() || extent.document() != document))
         return false;
     return true;
 }
diff --git a/third_party/WebKit/Source/core/editing/Position.h b/third_party/WebKit/Source/core/editing/Position.h
index 8b49ae6e..84d9221 100644
--- a/third_party/WebKit/Source/core/editing/Position.h
+++ b/third_party/WebKit/Source/core/editing/Position.h
@@ -137,11 +137,11 @@
     Node* anchorNode() const { return m_anchorNode.get(); }
 
     Document* document() const { return m_anchorNode ? &m_anchorNode->document() : 0; }
-    bool inDocument() const { return m_anchorNode && m_anchorNode->inDocument(); }
+    bool inShadowIncludingDocument() const { return m_anchorNode && m_anchorNode->inShadowIncludingDocument(); }
 
     bool isNull() const { return !m_anchorNode; }
     bool isNotNull() const { return m_anchorNode; }
-    bool isOrphan() const { return m_anchorNode && !m_anchorNode->inDocument(); }
+    bool isOrphan() const { return m_anchorNode && !m_anchorNode->inShadowIncludingDocument(); }
 
     int compareTo(const PositionTemplate<Strategy>&) const;
 
diff --git a/third_party/WebKit/Source/core/editing/VisibleSelection.cpp b/third_party/WebKit/Source/core/editing/VisibleSelection.cpp
index 40e5b828a..de26047 100644
--- a/third_party/WebKit/Source/core/editing/VisibleSelection.cpp
+++ b/third_party/WebKit/Source/core/editing/VisibleSelection.cpp
@@ -827,7 +827,7 @@
 template <typename Strategy>
 static bool isValidPosition(const PositionTemplate<Strategy>& position)
 {
-    if (!position.inDocument())
+    if (!position.inShadowIncludingDocument())
         return false;
 
     if (!position.isOffsetInAnchor())
diff --git a/third_party/WebKit/Source/core/editing/commands/ApplyBlockElementCommand.cpp b/third_party/WebKit/Source/core/editing/commands/ApplyBlockElementCommand.cpp
index 22407a7d..eca5b1e 100644
--- a/third_party/WebKit/Source/core/editing/commands/ApplyBlockElementCommand.cpp
+++ b/third_party/WebKit/Source/core/editing/commands/ApplyBlockElementCommand.cpp
@@ -155,11 +155,11 @@
         // indentIntoBlockquote could move more than one paragraph if the paragraph
         // is in a list item or a table. As a result, endAfterSelection could refer to a position
         // no longer in the document.
-        if (endAfterSelection.isNotNull() && !endAfterSelection.deepEquivalent().inDocument())
+        if (endAfterSelection.isNotNull() && !endAfterSelection.deepEquivalent().inShadowIncludingDocument())
             break;
         // Sanity check: Make sure our moveParagraph calls didn't remove endOfNextParagraph.deepEquivalent().anchorNode()
         // If somehow, e.g. mutation event handler, we did, return to prevent crashes.
-        if (endOfNextParagraph.isNotNull() && !endOfNextParagraph.deepEquivalent().inDocument())
+        if (endOfNextParagraph.isNotNull() && !endOfNextParagraph.deepEquivalent().inShadowIncludingDocument())
             return;
         endOfCurrentParagraph = endOfNextParagraph;
     }
diff --git a/third_party/WebKit/Source/core/editing/commands/ApplyStyleCommand.cpp b/third_party/WebKit/Source/core/editing/commands/ApplyStyleCommand.cpp
index a0bb6d8..d42b5dc 100644
--- a/third_party/WebKit/Source/core/editing/commands/ApplyStyleCommand.cpp
+++ b/third_party/WebKit/Source/core/editing/commands/ApplyStyleCommand.cpp
@@ -482,7 +482,7 @@
     ContainerNode* nextHighestAncestorWithUnicodeBidi = nullptr;
     int highestAncestorUnicodeBidi = 0;
     for (ContainerNode* n = node->parentNode(); n != block; n = n->parentNode()) {
-        int unicodeBidi = getIdentifierValue(CSSComputedStyleDeclaration::create(n).get(), CSSPropertyUnicodeBidi);
+        int unicodeBidi = getIdentifierValue(CSSComputedStyleDeclaration::create(n), CSSPropertyUnicodeBidi);
         if (unicodeBidi && unicodeBidi != CSSValueNormal) {
             highestAncestorUnicodeBidi = unicodeBidi;
             nextHighestAncestorWithUnicodeBidi = highestAncestorWithUnicodeBidi;
@@ -532,7 +532,7 @@
             continue;
 
         Element* element = toElement(n);
-        int unicodeBidi = getIdentifierValue(CSSComputedStyleDeclaration::create(element).get(), CSSPropertyUnicodeBidi);
+        int unicodeBidi = getIdentifierValue(CSSComputedStyleDeclaration::create(element), CSSPropertyUnicodeBidi);
         if (!unicodeBidi || unicodeBidi == CSSValueNormal)
             continue;
 
@@ -562,7 +562,7 @@
 {
     for (Node* n = startNode; n && n != enclosingNode; n = n->parentNode()) {
         if (n->isHTMLElement()
-            && EditingStyle::isEmbedOrIsolate(getIdentifierValue(CSSComputedStyleDeclaration::create(n).get(), CSSPropertyUnicodeBidi))) {
+            && EditingStyle::isEmbedOrIsolate(getIdentifierValue(CSSComputedStyleDeclaration::create(n), CSSPropertyUnicodeBidi))) {
             return toHTMLElement(n);
         }
     }
@@ -789,7 +789,7 @@
 
     bool startAndEndAreStillInDocument()
     {
-        return start && end && start->inDocument() && end->inDocument();
+        return start && end && start->inShadowIncludingDocument() && end->inShadowIncludingDocument();
     }
 
     DEFINE_INLINE_TRACE()
@@ -936,7 +936,7 @@
 {
     ASSERT(runStart && runEnd);
     RawPtr<Node> next = runStart;
-    for (RawPtr<Node> node = next; node && node->inDocument() && node != pastEndNode; node = next) {
+    for (RawPtr<Node> node = next; node && node->inShadowIncludingDocument() && node != pastEndNode; node = next) {
         if (editingIgnoresContent(node.get())) {
             ASSERT(!node->contains(pastEndNode.get()));
             next = NodeTraversal::nextSkippingChildren(*node);
@@ -953,7 +953,7 @@
         removeInlineStyleFromElement(style, &element, editingState, RemoveAlways);
         if (editingState->isAborted())
             return;
-        if (!element.inDocument()) {
+        if (!element.inShadowIncludingDocument()) {
             // FIXME: We might need to update the start and the end of current selection here but need a test.
             if (runStart == element)
                 runStart = previousSibling ? previousSibling->nextSibling() : parent->firstChild();
@@ -985,7 +985,7 @@
     if (editingState->isAborted())
         return false;
 
-    if (!element->inDocument())
+    if (!element->inShadowIncludingDocument())
         return removed;
 
     // If the node was converted to a span, the span may still contain relevant
@@ -1180,8 +1180,8 @@
 {
     ASSERT(start.isNotNull());
     ASSERT(end.isNotNull());
-    ASSERT(start.inDocument());
-    ASSERT(end.inDocument());
+    ASSERT(start.inShadowIncludingDocument());
+    ASSERT(end.inShadowIncludingDocument());
     ASSERT(Position::commonAncestorTreeScope(start, end));
     ASSERT(comparePositions(start, end) <= 0);
     // FIXME: We should assert that start/end are not in the middle of a text node.
@@ -1244,7 +1244,7 @@
             removeInlineStyleFromElement(style, elem.get(), editingState, RemoveIfNeeded, styleToPushDown.get());
             if (editingState->isAborted())
                 return;
-            if (!elem->inDocument()) {
+            if (!elem->inShadowIncludingDocument()) {
                 if (s.anchorNode() == elem) {
                     // Since elem must have been fully selected, and it is at the start
                     // of the selection, it is clear we can set the new s offset to 0.
@@ -1516,7 +1516,7 @@
 
 void ApplyStyleCommand::addInlineStyleIfNeeded(EditingStyle* style, RawPtr<Node> passedStart, RawPtr<Node> passedEnd, EditingState* editingState)
 {
-    if (!passedStart || !passedEnd || !passedStart->inDocument() || !passedEnd->inDocument())
+    if (!passedStart || !passedEnd || !passedStart->inShadowIncludingDocument() || !passedEnd->inShadowIncludingDocument())
         return;
 
     RawPtr<Node> start = passedStart;
@@ -1552,8 +1552,8 @@
 {
     RawPtr<Node> startNode = passedStart;
     RawPtr<Node> endNode = passedEnd;
-    ASSERT(startNode->inDocument());
-    ASSERT(endNode->inDocument());
+    ASSERT(startNode->inShadowIncludingDocument());
+    ASSERT(endNode->inShadowIncludingDocument());
 
     // Find appropriate font and span elements top-down.
     HTMLFontElement* fontContainer = nullptr;
@@ -1661,11 +1661,11 @@
     if (!node)
         return 0;
 
-    RawPtr<CSSComputedStyleDeclaration> style = CSSComputedStyleDeclaration::create(node);
+    CSSComputedStyleDeclaration* style = CSSComputedStyleDeclaration::create(node);
     if (!style)
         return 0;
 
-    RawPtr<CSSPrimitiveValue> value = static_pointer_cast<CSSPrimitiveValue>(style->getPropertyCSSValue(CSSPropertyFontSize));
+    CSSPrimitiveValue* value = toCSSPrimitiveValue(style->getPropertyCSSValue(CSSPropertyFontSize));
     if (!value)
         return 0;
 
diff --git a/third_party/WebKit/Source/core/editing/commands/CompositeEditCommand.cpp b/third_party/WebKit/Source/core/editing/commands/CompositeEditCommand.cpp
index 119bdb6b..5ec5142 100644
--- a/third_party/WebKit/Source/core/editing/commands/CompositeEditCommand.cpp
+++ b/third_party/WebKit/Source/core/editing/commands/CompositeEditCommand.cpp
@@ -364,7 +364,7 @@
         splitTextNode(toText(refChild), offset);
 
         // Mutation events (bug 22634) from the text node insertion may have removed the refChild
-        if (!refChild->inDocument())
+        if (!refChild->inShadowIncludingDocument())
             return;
         insertNodeBefore(insertChild, refChild, editingState);
     } else {
@@ -466,7 +466,7 @@
     // Returning a raw pointer here is OK because the command is retained by
     // applyCommandToComposite (thus retaining the span), and the span is also
     // in the DOM tree, and thus alive whie it has a parent.
-    ASSERT(command->spanElement()->inDocument());
+    ASSERT(command->spanElement()->inShadowIncludingDocument());
     return command->spanElement();
 }
 
@@ -1053,7 +1053,7 @@
     if (editingState->isAborted())
         return;
     // Clones of anchorNode have been pushed down, now remove it.
-    if (anchorNode->inDocument())
+    if (anchorNode->inShadowIncludingDocument())
         removeNodePreservingChildren(anchorNode, editingState);
 }
 
@@ -1100,7 +1100,7 @@
 
     // Scripts specified in javascript protocol may remove |outerNode|
     // during insertion, e.g. <iframe src="javascript:...">
-    if (!outerNode->inDocument())
+    if (!outerNode->inShadowIncludingDocument())
         return;
 
     // Handle the case of paragraphs with more than one node,
@@ -1311,11 +1311,11 @@
     if (editingState->isAborted())
         return;
 
-    ASSERT(destination.deepEquivalent().inDocument());
+    ASSERT(destination.deepEquivalent().inShadowIncludingDocument());
     cleanupAfterDeletion(editingState, destination);
     if (editingState->isAborted())
         return;
-    ASSERT(destination.deepEquivalent().inDocument());
+    ASSERT(destination.deepEquivalent().inShadowIncludingDocument());
 
     // Add a br if pruning an empty block level element caused a collapse. For example:
     // foo^
diff --git a/third_party/WebKit/Source/core/editing/commands/DeleteSelectionCommand.cpp b/third_party/WebKit/Source/core/editing/commands/DeleteSelectionCommand.cpp
index d37e6d0..b098caf7 100644
--- a/third_party/WebKit/Source/core/editing/commands/DeleteSelectionCommand.cpp
+++ b/third_party/WebKit/Source/core/editing/commands/DeleteSelectionCommand.cpp
@@ -558,7 +558,7 @@
             }
         }
 
-        if (m_downstreamEnd.anchorNode() != startNode && !m_upstreamStart.anchorNode()->isDescendantOf(m_downstreamEnd.anchorNode()) && m_downstreamEnd.inDocument() && m_downstreamEnd.computeEditingOffset() >= caretMinOffset(m_downstreamEnd.anchorNode())) {
+        if (m_downstreamEnd.anchorNode() != startNode && !m_upstreamStart.anchorNode()->isDescendantOf(m_downstreamEnd.anchorNode()) && m_downstreamEnd.inShadowIncludingDocument() && m_downstreamEnd.computeEditingOffset() >= caretMinOffset(m_downstreamEnd.anchorNode())) {
             if (m_downstreamEnd.atLastEditingPositionForNode() && !canHaveChildrenForEditing(m_downstreamEnd.anchorNode())) {
                 // The node itself is fully selected, not just its contents.  Delete it.
                 removeNode(m_downstreamEnd.anchorNode(), editingState);
@@ -575,7 +575,7 @@
                 // know how many children to remove.
                 // FIXME: Make m_upstreamStart a position we update as we remove content, then we can
                 // always know which children to remove.
-                } else if (!(startNodeWasDescendantOfEndNode && !m_upstreamStart.inDocument())) {
+                } else if (!(startNodeWasDescendantOfEndNode && !m_upstreamStart.inShadowIncludingDocument())) {
                     int offset = 0;
                     if (m_upstreamStart.anchorNode()->isDescendantOf(m_downstreamEnd.anchorNode())) {
                         Node* n = m_upstreamStart.anchorNode();
@@ -633,7 +633,7 @@
     ASSERT(!m_pruneStartBlockIfNecessary);
 
     // FIXME: Deletion should adjust selection endpoints as it removes nodes so that we never get into this state (4099839).
-    if (!m_downstreamEnd.inDocument() || !m_upstreamStart.inDocument())
+    if (!m_downstreamEnd.inShadowIncludingDocument() || !m_upstreamStart.inShadowIncludingDocument())
         return;
 
     // FIXME: The deletion algorithm shouldn't let this happen.
@@ -718,7 +718,7 @@
 
 void DeleteSelectionCommand::removePreviouslySelectedEmptyTableRows(EditingState* editingState)
 {
-    if (m_endTableRow && m_endTableRow->inDocument() && m_endTableRow != m_startTableRow) {
+    if (m_endTableRow && m_endTableRow->inShadowIncludingDocument() && m_endTableRow != m_startTableRow) {
         Node* row = m_endTableRow->previousSibling();
         while (row && row != m_startTableRow) {
             RawPtr<Node> previousRow = row->previousSibling();
@@ -735,7 +735,7 @@
     }
 
     // Remove empty rows after the start row.
-    if (m_startTableRow && m_startTableRow->inDocument() && m_startTableRow != m_endTableRow) {
+    if (m_startTableRow && m_startTableRow->inShadowIncludingDocument() && m_startTableRow != m_endTableRow) {
         Node* row = m_startTableRow->nextSibling();
         while (row && row != m_endTableRow) {
             RawPtr<Node> nextRow = row->nextSibling();
@@ -748,7 +748,7 @@
         }
     }
 
-    if (m_endTableRow && m_endTableRow->inDocument() && m_endTableRow != m_startTableRow) {
+    if (m_endTableRow && m_endTableRow->inShadowIncludingDocument() && m_endTableRow != m_startTableRow) {
         if (isTableRowEmpty(m_endTableRow.get())) {
             // Don't remove m_endTableRow if it's where we're putting the ending
             // selection.
@@ -916,7 +916,7 @@
         }
         // handleGeneralDelete cause DOM mutation events so |m_endingPosition|
         // can be out of document.
-        if (m_endingPosition.inDocument()) {
+        if (m_endingPosition.inShadowIncludingDocument()) {
             insertNodeAt(placeholder.get(), m_endingPosition, editingState);
             if (editingState->isAborted())
                 return;
diff --git a/third_party/WebKit/Source/core/editing/commands/IndentOutdentCommand.cpp b/third_party/WebKit/Source/core/editing/commands/IndentOutdentCommand.cpp
index 34f6042..51c2e06b 100644
--- a/third_party/WebKit/Source/core/editing/commands/IndentOutdentCommand.cpp
+++ b/third_party/WebKit/Source/core/editing/commands/IndentOutdentCommand.cpp
@@ -262,10 +262,10 @@
         // outdentParagraph could move more than one paragraph if the paragraph
         // is in a list item. As a result, endAfterSelection and endOfNextParagraph
         // could refer to positions no longer in the document.
-        if (endAfterSelection.isNotNull() && !endAfterSelection.deepEquivalent().inDocument())
+        if (endAfterSelection.isNotNull() && !endAfterSelection.deepEquivalent().inShadowIncludingDocument())
             break;
 
-        if (endOfNextParagraph.isNotNull() && !endOfNextParagraph.deepEquivalent().inDocument()) {
+        if (endOfNextParagraph.isNotNull() && !endOfNextParagraph.deepEquivalent().inShadowIncludingDocument()) {
             endOfCurrentParagraph = createVisiblePosition(endingSelection().end());
             endOfNextParagraph = endOfParagraph(nextPositionOf(endOfCurrentParagraph));
         }
diff --git a/third_party/WebKit/Source/core/editing/commands/InsertLineBreakCommand.cpp b/third_party/WebKit/Source/core/editing/commands/InsertLineBreakCommand.cpp
index 7abb0c5..195bdae6 100644
--- a/third_party/WebKit/Source/core/editing/commands/InsertLineBreakCommand.cpp
+++ b/third_party/WebKit/Source/core/editing/commands/InsertLineBreakCommand.cpp
@@ -156,7 +156,7 @@
             deleteInsignificantTextDownstream(endingPosition);
             ASSERT(!textNode->layoutObject() || textNode->layoutObject()->style()->collapseWhiteSpace());
             // Deleting insignificant whitespace will remove textNode if it contains nothing but insignificant whitespace.
-            if (textNode->inDocument()) {
+            if (textNode->inShadowIncludingDocument()) {
                 insertTextIntoNode(textNode, 0, nonBreakingSpaceString());
             } else {
                 RawPtr<Text> nbspNode = document().createTextNode(nonBreakingSpaceString());
diff --git a/third_party/WebKit/Source/core/editing/commands/InsertListCommand.cpp b/third_party/WebKit/Source/core/editing/commands/InsertListCommand.cpp
index 35f06d1..96bd555 100644
--- a/third_party/WebKit/Source/core/editing/commands/InsertListCommand.cpp
+++ b/third_party/WebKit/Source/core/editing/commands/InsertListCommand.cpp
@@ -175,7 +175,7 @@
                 // infinite loop and because there is no more work to be done.
                 // FIXME(<rdar://problem/5983974>): The endingSelection() may be incorrect here.  Compute
                 // the new location of endOfSelection and use it as the end of the new selection.
-                if (!startOfLastParagraph.deepEquivalent().inDocument())
+                if (!startOfLastParagraph.deepEquivalent().inShadowIncludingDocument())
                     return;
                 setEndingSelection(startOfCurrentParagraph);
 
@@ -288,7 +288,7 @@
             // Manually remove listNode because moveParagraphWithClones sometimes leaves it behind in the document.
             // See the bug 33668 and editing/execCommand/insert-list-orphaned-item-with-nested-lists.html.
             // FIXME: This might be a bug in moveParagraphWithClones or deleteSelection.
-            if (listElement && listElement->inDocument()) {
+            if (listElement && listElement->inShadowIncludingDocument()) {
                 removeNode(listElement, editingState);
                 if (editingState->isAborted())
                     return false;
diff --git a/third_party/WebKit/Source/core/editing/commands/InsertTextCommand.cpp b/third_party/WebKit/Source/core/editing/commands/InsertTextCommand.cpp
index 0960b60..76ff5cc 100644
--- a/third_party/WebKit/Source/core/editing/commands/InsertTextCommand.cpp
+++ b/third_party/WebKit/Source/core/editing/commands/InsertTextCommand.cpp
@@ -180,7 +180,7 @@
     ASSERT(startPosition.computeContainerNode());
     Position positionBeforeStartNode(positionInParentBeforeNode(*startPosition.computeContainerNode()));
     deleteInsignificantText(startPosition, mostForwardCaretPosition(startPosition));
-    if (!startPosition.inDocument())
+    if (!startPosition.inShadowIncludingDocument())
         startPosition = positionBeforeStartNode;
     if (!isVisuallyEquivalentCandidate(startPosition))
         startPosition = mostForwardCaretPosition(startPosition);
diff --git a/third_party/WebKit/Source/core/editing/commands/MoveSelectionCommand.cpp b/third_party/WebKit/Source/core/editing/commands/MoveSelectionCommand.cpp
index 655b95e..f94f55c 100644
--- a/third_party/WebKit/Source/core/editing/commands/MoveSelectionCommand.cpp
+++ b/third_party/WebKit/Source/core/editing/commands/MoveSelectionCommand.cpp
@@ -63,7 +63,7 @@
     // set the destination to the ending point after the deletion.
     // Fixes: <rdar://problem/3910425> REGRESSION (Mail): Crash in ReplaceSelectionCommand;
     //        selection is empty, leading to null deref
-    if (!pos.inDocument())
+    if (!pos.inShadowIncludingDocument())
         pos = endingSelection().start();
 
     cleanupAfterDeletion(editingState, createVisiblePosition(pos));
@@ -71,7 +71,7 @@
         return;
 
     setEndingSelection(VisibleSelection(pos, endingSelection().affinity(), endingSelection().isDirectional()));
-    if (!pos.inDocument()) {
+    if (!pos.inShadowIncludingDocument()) {
         // Document was modified out from under us.
         return;
     }
diff --git a/third_party/WebKit/Source/core/editing/commands/ReplaceNodeWithSpanCommand.cpp b/third_party/WebKit/Source/core/editing/commands/ReplaceNodeWithSpanCommand.cpp
index e552937..127a973e 100644
--- a/third_party/WebKit/Source/core/editing/commands/ReplaceNodeWithSpanCommand.cpp
+++ b/third_party/WebKit/Source/core/editing/commands/ReplaceNodeWithSpanCommand.cpp
@@ -50,7 +50,7 @@
 
 static void swapInNodePreservingAttributesAndChildren(HTMLElement* newElement, HTMLElement& elementToReplace)
 {
-    ASSERT(elementToReplace.inDocument());
+    ASSERT(elementToReplace.inShadowIncludingDocument());
     RawPtr<ContainerNode> parentNode = elementToReplace.parentNode();
     parentNode->insertBefore(newElement, &elementToReplace);
 
@@ -67,7 +67,7 @@
 
 void ReplaceNodeWithSpanCommand::doApply(EditingState*)
 {
-    if (!m_elementToReplace->inDocument())
+    if (!m_elementToReplace->inShadowIncludingDocument())
         return;
     if (!m_spanElement)
         m_spanElement = HTMLSpanElement::create(m_elementToReplace->document());
@@ -76,7 +76,7 @@
 
 void ReplaceNodeWithSpanCommand::doUnapply()
 {
-    if (!m_spanElement->inDocument())
+    if (!m_spanElement->inShadowIncludingDocument())
         return;
     swapInNodePreservingAttributesAndChildren(m_elementToReplace.get(), *m_spanElement);
 }
diff --git a/third_party/WebKit/Source/core/editing/commands/ReplaceSelectionCommand.cpp b/third_party/WebKit/Source/core/editing/commands/ReplaceSelectionCommand.cpp
index b600cbc..9a7ab4a 100644
--- a/third_party/WebKit/Source/core/editing/commands/ReplaceSelectionCommand.cpp
+++ b/third_party/WebKit/Source/core/editing/commands/ReplaceSelectionCommand.cpp
@@ -677,7 +677,7 @@
             continue;
         // moveElementOutOfAncestor() in a previous iteration might have failed,
         // and |node| might have been detached from the document tree.
-        if (!node->inDocument())
+        if (!node->inShadowIncludingDocument())
             continue;
 
         HTMLElement& element = toHTMLElement(*node);
@@ -1196,7 +1196,7 @@
     }
 
     // Mutation events (bug 22634) may have already removed the inserted content
-    if (!refNode->inDocument())
+    if (!refNode->inShadowIncludingDocument())
         return;
 
     bool plainTextFragment = isPlainTextMarkup(refNode.get());
@@ -1210,7 +1210,7 @@
         insertedNodes.respondToNodeInsertion(*node);
 
         // Mutation events (bug 22634) may have already removed the inserted content
-        if (!node->inDocument())
+        if (!node->inShadowIncludingDocument())
             return;
 
         refNode = node;
@@ -1229,12 +1229,12 @@
     }
 
     // Mutation events (bug 20161) may have already removed the inserted content
-    if (!insertedNodes.firstNodeInserted() || !insertedNodes.firstNodeInserted()->inDocument())
+    if (!insertedNodes.firstNodeInserted() || !insertedNodes.firstNodeInserted()->inShadowIncludingDocument())
         return;
 
     // Scripts specified in javascript protocol may remove |enclosingBlockOfInsertionPos|
     // during insertion, e.g. <iframe src="javascript:...">
-    if (enclosingBlockOfInsertionPos && !enclosingBlockOfInsertionPos->inDocument())
+    if (enclosingBlockOfInsertionPos && !enclosingBlockOfInsertionPos->inShadowIncludingDocument())
         enclosingBlockOfInsertionPos = nullptr;
 
     VisiblePosition startOfInsertedContent = createVisiblePosition(firstPositionInOrBeforeNode(insertedNodes.firstNodeInserted()));
@@ -1309,7 +1309,7 @@
             if (editingState->isAborted())
                 return;
             // Mutation events (bug 22634) triggered by inserting the <br> might have removed the content we're about to move
-            if (!startOfParagraphToMove.deepEquivalent().inDocument())
+            if (!startOfParagraphToMove.deepEquivalent().inShadowIncludingDocument())
                 return;
         }
 
@@ -1389,7 +1389,7 @@
 
 bool ReplaceSelectionCommand::shouldRemoveEndBR(HTMLBRElement* endBR, const VisiblePosition& originalVisPosBeforeEndBR)
 {
-    if (!endBR || !endBR->inDocument())
+    if (!endBR || !endBR->inShadowIncludingDocument())
         return false;
 
     VisiblePosition visiblePos = createVisiblePosition(positionBeforeNode(endBR));
diff --git a/third_party/WebKit/Source/core/editing/iterators/SearchBuffer.cpp b/third_party/WebKit/Source/core/editing/iterators/SearchBuffer.cpp
index f9d370e..d278e4f 100644
--- a/third_party/WebKit/Source/core/editing/iterators/SearchBuffer.cpp
+++ b/third_party/WebKit/Source/core/editing/iterators/SearchBuffer.cpp
@@ -29,7 +29,7 @@
 #include "core/dom/Document.h"
 #include "core/editing/iterators/CharacterIterator.h"
 #include "core/editing/iterators/SimplifiedBackwardsTextIterator.h"
-#include "platform/fonts/Character.h"
+#include "platform/text/Character.h"
 #include "platform/text/TextBoundaries.h"
 #include "platform/text/TextBreakIteratorInternalICU.h"
 #include "platform/text/UnicodeUtilities.h"
@@ -423,7 +423,7 @@
 static EphemeralRangeTemplate<Strategy> findPlainTextAlgorithm(const EphemeralRangeTemplate<Strategy>& inputRange, const String& target, FindOptions options)
 {
     // CharacterIterator requires layoutObjects to be up-to-date.
-    if (!inputRange.startPosition().inDocument())
+    if (!inputRange.startPosition().inShadowIncludingDocument())
         return EphemeralRangeTemplate<Strategy>();
     ASSERT(inputRange.startPosition().document() == inputRange.endPosition().document());
 
diff --git a/third_party/WebKit/Source/core/editing/spellcheck/SpellCheckRequester.cpp b/third_party/WebKit/Source/core/editing/spellcheck/SpellCheckRequester.cpp
index 082e02fb..054dedc 100644
--- a/third_party/WebKit/Source/core/editing/spellcheck/SpellCheckRequester.cpp
+++ b/third_party/WebKit/Source/core/editing/spellcheck/SpellCheckRequester.cpp
@@ -52,9 +52,9 @@
     , m_requestNumber(requestNumber)
 {
     ASSERT(m_checkingRange);
-    ASSERT(m_checkingRange->inDocument());
+    ASSERT(m_checkingRange->inShadowIncludingDocument());
     ASSERT(m_paragraphRange);
-    ASSERT(m_paragraphRange->inDocument());
+    ASSERT(m_paragraphRange->inShadowIncludingDocument());
     ASSERT(m_rootEditableElement);
 }
 
@@ -117,7 +117,7 @@
 
 bool SpellCheckRequest::isValid() const
 {
-    return m_checkingRange->inDocument() && m_paragraphRange->inDocument() && m_rootEditableElement->inDocument();
+    return m_checkingRange->inShadowIncludingDocument() && m_paragraphRange->inShadowIncludingDocument() && m_rootEditableElement->inShadowIncludingDocument();
 }
 
 void SpellCheckRequest::didSucceed(const Vector<TextCheckingResult>& results)
diff --git a/third_party/WebKit/Source/core/editing/spellcheck/SpellChecker.cpp b/third_party/WebKit/Source/core/editing/spellcheck/SpellChecker.cpp
index 2a09955..d8f5e952e 100644
--- a/third_party/WebKit/Source/core/editing/spellcheck/SpellChecker.cpp
+++ b/third_party/WebKit/Source/core/editing/spellcheck/SpellChecker.cpp
@@ -804,7 +804,7 @@
             && closeTyping
             && !isSelectionInTextField(oldSelection)
             && (isSelectionInTextArea(oldSelection) || oldSelection.isContentEditable())
-            && oldSelection.start().inDocument()) {
+            && oldSelection.start().inShadowIncludingDocument()) {
             spellCheckOldSelection(oldSelection, newAdjacentWords);
         }
     }
diff --git a/third_party/WebKit/Source/core/editing/state_machines/BackspaceStateMachine.cpp b/third_party/WebKit/Source/core/editing/state_machines/BackspaceStateMachine.cpp
index 28cfb38c..3ea60fb 100644
--- a/third_party/WebKit/Source/core/editing/state_machines/BackspaceStateMachine.cpp
+++ b/third_party/WebKit/Source/core/editing/state_machines/BackspaceStateMachine.cpp
@@ -4,8 +4,7 @@
 
 #include "core/editing/state_machines/BackspaceStateMachine.h"
 
-// TODO(nona):Move Character.h to platform/text
-#include "platform/fonts/Character.h"
+#include "platform/text/Character.h"
 #include "wtf/text/CharacterNames.h"
 #include "wtf/text/Unicode.h"
 #include <ostream> // NOLINT
diff --git a/third_party/WebKit/Source/core/editing/state_machines/BackwardGraphemeBoundaryStateMachine.cpp b/third_party/WebKit/Source/core/editing/state_machines/BackwardGraphemeBoundaryStateMachine.cpp
index c43d014..eef83ec1 100644
--- a/third_party/WebKit/Source/core/editing/state_machines/BackwardGraphemeBoundaryStateMachine.cpp
+++ b/third_party/WebKit/Source/core/editing/state_machines/BackwardGraphemeBoundaryStateMachine.cpp
@@ -6,7 +6,7 @@
 
 #include "core/editing/state_machines/StateMachineUtil.h"
 #include "core/editing/state_machines/TextSegmentationMachineState.h"
-#include "platform/fonts/Character.h"
+#include "platform/text/Character.h"
 #include "wtf/text/Unicode.h"
 #include <ostream> // NOLINT
 
diff --git a/third_party/WebKit/Source/core/editing/state_machines/ForwardGraphemeBoundaryStateMachine.cpp b/third_party/WebKit/Source/core/editing/state_machines/ForwardGraphemeBoundaryStateMachine.cpp
new file mode 100644
index 0000000..1caa4b8
--- /dev/null
+++ b/third_party/WebKit/Source/core/editing/state_machines/ForwardGraphemeBoundaryStateMachine.cpp
@@ -0,0 +1,266 @@
+// Copyright 2016 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 "core/editing/state_machines/ForwardGraphemeBoundaryStateMachine.h"
+
+#include "core/editing/state_machines/StateMachineUtil.h"
+#include "core/editing/state_machines/TextSegmentationMachineState.h"
+#include "platform/text/Character.h"
+#include "wtf/text/Unicode.h"
+#include <ostream> // NOLINT
+
+namespace blink {
+
+#define FOR_EACH_FORWARD_GRAPHEME_BOUNDARY_STATE(V)                      \
+    /* Counting preceding regional indicators. This is initial state. */ \
+    V(CountRIS)                                                          \
+    /* Waiting lead surrogate during counting regional indicators. */    \
+    V(CountRISWaitLeadSurrogate)                                         \
+    /* Waiting first following code unit. */                             \
+    V(StartForward)                                                      \
+    /* Waiting trail surrogate for the first following code point. */    \
+    V(StartForwardWaitTrailSurrgate)                                     \
+    /* Searching grapheme boundary. */                                   \
+    V(Search)                                                            \
+    /* Waiting trail surrogate during searching grapheme boundary. */    \
+    V(SearchWaitTrailSurrogate)                                          \
+    /* The state machine has stopped. */                                 \
+    V(Finished)
+
+enum class ForwardGraphemeBoundaryStateMachine::InternalState {
+#define V(name) name,
+    FOR_EACH_FORWARD_GRAPHEME_BOUNDARY_STATE(V)
+#undef V
+};
+
+std::ostream& operator<<(std::ostream& os,
+    ForwardGraphemeBoundaryStateMachine::InternalState state)
+{
+    static const char* const texts[] = {
+#define V(name) #name,
+    FOR_EACH_FORWARD_GRAPHEME_BOUNDARY_STATE(V)
+#undef V
+    };
+    const auto& it = std::begin(texts) + static_cast<size_t>(state);
+    DCHECK_GE(it, std::begin(texts)) << "Unknown state value";
+    DCHECK_LT(it, std::end(texts)) << "Unknown state value";
+    return os << *it;
+}
+
+ForwardGraphemeBoundaryStateMachine::ForwardGraphemeBoundaryStateMachine()
+    : m_internalState(InternalState::CountRIS)
+{
+}
+
+TextSegmentationMachineState
+ForwardGraphemeBoundaryStateMachine::feedPrecedingCodeUnit(UChar codeUnit)
+{
+    DCHECK_EQ(m_prevCodePoint, 0);
+    DCHECK_EQ(m_boundaryOffset, 0);
+    switch (m_internalState) {
+    case InternalState::CountRIS:
+        DCHECK_EQ(m_pendingCodeUnit, 0);
+        if (U16_IS_TRAIL(codeUnit)) {
+            m_pendingCodeUnit = codeUnit;
+            return moveToNextState(InternalState::CountRISWaitLeadSurrogate);
+        }
+        return moveToNextState(InternalState::StartForward);
+    case InternalState::CountRISWaitLeadSurrogate:
+        DCHECK_NE(m_pendingCodeUnit, 0);
+        if (U16_IS_LEAD(codeUnit)) {
+            const UChar32 codePoint =
+                U16_GET_SUPPLEMENTARY(codeUnit, m_pendingCodeUnit);
+            m_pendingCodeUnit = 0;
+            if (Character::isRegionalIndicator(codePoint)) {
+                ++m_precedingRISCount;
+                return moveToNextState(InternalState::CountRIS);
+            }
+        }
+        m_pendingCodeUnit = 0;
+        return moveToNextState(InternalState::StartForward);
+    case InternalState::StartForward: // Fallthrough
+    case InternalState::StartForwardWaitTrailSurrgate: // Fallthrough
+    case InternalState::Search: // Fallthrough
+    case InternalState::SearchWaitTrailSurrogate: // Fallthrough
+        NOTREACHED() << "Do not call feedPrecedingCodeUnit() once "
+            << TextSegmentationMachineState::NeedFollowingCodeUnit
+            << " is returned. InternalState: " << m_internalState;
+        return finish();
+    case InternalState::Finished:
+        NOTREACHED() << "Do not call feedPrecedingCodeUnit() once it finishes.";
+        return finish();
+    }
+    NOTREACHED() << "Unhandled state: " << m_internalState;
+    return finish();
+}
+
+TextSegmentationMachineState
+ForwardGraphemeBoundaryStateMachine::feedFollowingCodeUnit(UChar codeUnit)
+{
+    switch (m_internalState) {
+    case InternalState::CountRIS: // Fallthrough
+    case InternalState::CountRISWaitLeadSurrogate:
+        NOTREACHED() << "Do not call feedFollowingCodeUnit() until "
+            << TextSegmentationMachineState::NeedFollowingCodeUnit
+            << " is returned. InternalState: " << m_internalState;
+        return finish();
+    case InternalState::StartForward:
+        DCHECK_EQ(m_prevCodePoint, 0);
+        DCHECK_EQ(m_boundaryOffset, 0);
+        DCHECK_EQ(m_pendingCodeUnit, 0);
+        if (U16_IS_TRAIL(codeUnit)) {
+            // Lonely trail surrogate.
+            m_boundaryOffset = 1;
+            return finish();
+        }
+        if (U16_IS_LEAD(codeUnit)) {
+            m_pendingCodeUnit = codeUnit;
+            return moveToNextState(
+                InternalState::StartForwardWaitTrailSurrgate);
+        }
+        m_prevCodePoint = codeUnit;
+        m_boundaryOffset = 1;
+        return moveToNextState(InternalState::Search);
+    case InternalState::StartForwardWaitTrailSurrgate:
+        DCHECK_EQ(m_prevCodePoint, 0);
+        DCHECK_EQ(m_boundaryOffset, 0);
+        DCHECK_NE(m_pendingCodeUnit, 0);
+        if (U16_IS_TRAIL(codeUnit)) {
+            m_prevCodePoint =
+                U16_GET_SUPPLEMENTARY(m_pendingCodeUnit, codeUnit);
+            m_boundaryOffset = 2;
+            m_pendingCodeUnit = 0;
+            return moveToNextState(InternalState::Search);
+        }
+        // Lonely lead surrogate.
+        m_boundaryOffset = 1;
+        return finish();
+    case InternalState::Search:
+        DCHECK_NE(m_prevCodePoint, 0);
+        DCHECK_NE(m_boundaryOffset, 0);
+        DCHECK_EQ(m_pendingCodeUnit, 0);
+        if (U16_IS_LEAD(codeUnit)) {
+            m_pendingCodeUnit = codeUnit;
+            return moveToNextState(InternalState::SearchWaitTrailSurrogate);
+        }
+        if (U16_IS_TRAIL(codeUnit))
+            return finish(); // Lonely trail surrogate.
+        if (isGraphemeBreak(m_prevCodePoint, codeUnit))
+            return finish();
+        m_prevCodePoint = codeUnit;
+        m_boundaryOffset += 1;
+        return staySameState();
+    case InternalState::SearchWaitTrailSurrogate:
+        DCHECK_NE(m_prevCodePoint, 0);
+        DCHECK_NE(m_boundaryOffset, 0);
+        DCHECK_NE(m_pendingCodeUnit, 0);
+        if (!U16_IS_TRAIL(codeUnit))
+            return finish(); // Lonely lead surrogate.
+
+        {
+            const UChar32 codePoint =
+                U16_GET_SUPPLEMENTARY(m_pendingCodeUnit, codeUnit);
+            m_pendingCodeUnit = 0;
+            if (Character::isRegionalIndicator(m_prevCodePoint)
+                && Character::isRegionalIndicator(codePoint)) {
+                if (m_precedingRISCount % 2 == 0) {
+                    // Odd numbered RI case, note that m_prevCodePoint is also
+                    // RI.
+                    m_boundaryOffset += 2;
+                }
+                return finish();
+            }
+            if (isGraphemeBreak(m_prevCodePoint, codePoint))
+                return finish();
+            m_prevCodePoint = codePoint;
+            m_boundaryOffset += 2;
+            return moveToNextState(InternalState::Search);
+        }
+    case InternalState::Finished:
+        NOTREACHED() << "Do not call feedFollowingCodeUnit() once it finishes.";
+        return finish();
+    }
+    NOTREACHED() << "Unhandled staet: " << m_internalState;
+    return finish();
+}
+
+TextSegmentationMachineState
+ForwardGraphemeBoundaryStateMachine::tellEndOfPrecedingText()
+{
+    DCHECK(m_internalState == InternalState::CountRIS
+        || m_internalState == InternalState::CountRISWaitLeadSurrogate)
+        << "Do not call tellEndOfPrecedingText() once "
+        << TextSegmentationMachineState::NeedFollowingCodeUnit
+        << " is returned. InternalState: " << m_internalState;
+
+    // Clear pending code unit since preceding buffer may end with lonely trail
+    // surrogate. We can just ignore it since preceding buffer is only used for
+    // counting preceding regional indicators.
+    m_pendingCodeUnit = 0;
+    return moveToNextState(InternalState::StartForward);
+}
+
+int ForwardGraphemeBoundaryStateMachine::finalizeAndGetBoundaryOffset()
+{
+    if (m_internalState != InternalState::Finished)
+        finishWithEndOfText();
+    DCHECK_GE(m_boundaryOffset, 0);
+    return m_boundaryOffset;
+}
+
+void ForwardGraphemeBoundaryStateMachine::reset()
+{
+    m_pendingCodeUnit = 0;
+    m_boundaryOffset = 0;
+    m_precedingRISCount = 0;
+    m_prevCodePoint = 0;
+    m_internalState = InternalState::CountRIS;
+}
+
+TextSegmentationMachineState ForwardGraphemeBoundaryStateMachine::finish()
+{
+    DCHECK_NE(m_internalState, InternalState::Finished);
+    m_internalState = InternalState::Finished;
+    return TextSegmentationMachineState::Finished;
+}
+
+TextSegmentationMachineState
+ForwardGraphemeBoundaryStateMachine::moveToNextState(InternalState nextState)
+{
+    DCHECK_NE(nextState, InternalState::Finished) << "Use finish() instead";
+    DCHECK_NE(nextState, m_internalState) << "Use staySameSatate() instead";
+    m_internalState = nextState;
+    if (nextState == InternalState::StartForward)
+        return TextSegmentationMachineState::NeedFollowingCodeUnit;
+    return TextSegmentationMachineState::NeedMoreCodeUnit;
+}
+
+TextSegmentationMachineState
+ForwardGraphemeBoundaryStateMachine::staySameState()
+{
+    DCHECK_EQ(m_internalState, InternalState::Search)
+        << "Only Search can stay the same state.";
+    return TextSegmentationMachineState::NeedMoreCodeUnit;
+}
+
+void ForwardGraphemeBoundaryStateMachine::finishWithEndOfText()
+{
+    switch (m_internalState) {
+    case InternalState::CountRIS: // Fallthrough
+    case InternalState::CountRISWaitLeadSurrogate: // Fallthrough
+    case InternalState::StartForward: // Fallthrough
+        return; // Haven't search anything to forward. Just finish.
+    case InternalState::StartForwardWaitTrailSurrgate:
+        // Lonely lead surrogate.
+        m_boundaryOffset = 1;
+        return;
+    case InternalState::Search: // Fallthrough
+    case InternalState::SearchWaitTrailSurrogate: // Fallthrough
+        return;
+    case InternalState::Finished: // Fallthrough
+        NOTREACHED() << "Do not call finishWithEndOfText() once it finishes.";
+    }
+    NOTREACHED() << "Unhandled state: " << m_internalState;
+}
+} // namespace blink
diff --git a/third_party/WebKit/Source/core/editing/state_machines/ForwardGraphemeBoundaryStateMachine.h b/third_party/WebKit/Source/core/editing/state_machines/ForwardGraphemeBoundaryStateMachine.h
new file mode 100644
index 0000000..d330e10
--- /dev/null
+++ b/third_party/WebKit/Source/core/editing/state_machines/ForwardGraphemeBoundaryStateMachine.h
@@ -0,0 +1,76 @@
+// Copyright 2016 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 ForwardGraphemeBoundaryStateMachine_h
+#define ForwardGraphemeBoundaryStateMachine_h
+
+#include "core/CoreExport.h"
+#include "core/editing/state_machines/TextSegmentationMachineState.h"
+#include "wtf/Allocator.h"
+#include "wtf/Noncopyable.h"
+#include "wtf/text/Unicode.h"
+#include <iosfwd>
+
+namespace blink {
+
+class CORE_EXPORT ForwardGraphemeBoundaryStateMachine {
+    STACK_ALLOCATED();
+    WTF_MAKE_NONCOPYABLE(ForwardGraphemeBoundaryStateMachine);
+
+public:
+    ForwardGraphemeBoundaryStateMachine();
+
+    // Find boundary offset by feeding preceding text.
+    // This method must not be called after feedFollowingCodeUnit().
+    TextSegmentationMachineState feedPrecedingCodeUnit(UChar codeUnit);
+
+    // Tells the end of preceding text to the state machine.
+    TextSegmentationMachineState tellEndOfPrecedingText();
+
+    // Find boundary offset by feeding following text.
+    // This method must be called after feedPrecedingCodeUnit() returns
+    // NeedsFollowingCodeUnit.
+    TextSegmentationMachineState feedFollowingCodeUnit(UChar codeUnit);
+
+    // Returns the next boundary offset. This method finalizes the state machine
+    // if it is not finished.
+    int finalizeAndGetBoundaryOffset();
+
+    // Resets the internal state to the initial state.
+    void reset();
+
+private:
+    enum class InternalState;
+    friend std::ostream& operator<<(std::ostream&, InternalState);
+
+    TextSegmentationMachineState moveToNextState(InternalState);
+
+    TextSegmentationMachineState staySameState();
+
+    // Updates the internal state to InternalState::Finished then
+    // returnsTextSegmentationMachineState::Finished.
+    TextSegmentationMachineState finish();
+
+    // Handles end of text. This method always finishes the state machine.
+    void finishWithEndOfText();
+
+    // Used for composing supplementary code point with surrogate pairs.
+    UChar m_pendingCodeUnit = 0;
+
+    // The code point immediately before the m_BoundaryOffset.
+    UChar32 m_prevCodePoint = 0;
+
+    // The relative offset from the begging of this state machine.
+    int m_boundaryOffset = 0;
+
+    // The number of regional indicator symbols preceding to the begging offset.
+    int m_precedingRISCount = 0;
+
+    // The internal state.
+    InternalState m_internalState;
+};
+
+} // namespace blink
+
+#endif
diff --git a/third_party/WebKit/Source/core/editing/state_machines/ForwardGraphemeBoundaryStateMachineTest.cpp b/third_party/WebKit/Source/core/editing/state_machines/ForwardGraphemeBoundaryStateMachineTest.cpp
new file mode 100644
index 0000000..f27ecaf
--- /dev/null
+++ b/third_party/WebKit/Source/core/editing/state_machines/ForwardGraphemeBoundaryStateMachineTest.cpp
@@ -0,0 +1,629 @@
+// Copyright 2016 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 "core/editing/state_machines/ForwardGraphemeBoundaryStateMachine.h"
+
+#include "core/editing/state_machines/StateMachineTestUtil.h"
+#include "testing/gtest/include/gtest/gtest.h"
+#include "wtf/text/CharacterNames.h"
+
+namespace blink {
+
+// Notations:
+// | indicates inidicates initial offset position.
+// SOT indicates start of text.
+// EOT indicates end of text.
+// [Lead] indicates broken lonely lead surrogate.
+// [Trail] indicates broken lonely trail surrogate.
+// [U] indicates regional indicator symbol U.
+// [S] indicates regional indicator symbol S.
+
+namespace {
+// kWatch kVS16, kEye kVS16 are valid standardized variants.
+const UChar32 kWatch = 0x231A;
+const UChar32 kEye = WTF::Unicode::eyeCharacter;
+const UChar32 kVS16 = 0xFE0F;
+
+// kHanBMP KVS17, kHanSIP kVS17 are valie IVD sequences.
+const UChar32 kHanBMP = 0x845B;
+const UChar32 kHanSIP = 0x20000;
+const UChar32 kVS17 = 0xE0100;
+
+// Following lead/trail values are used for invalid surrogate pairs.
+const UChar kLead = 0xD83D;
+const UChar kTrail = 0xDC66;
+
+// U+1F1FA is REGIONAL INDICATOR SYMBOL LETTER U
+const UChar32 kRisU = 0x1F1FA;
+// U+1F1F8 is REGIONAL INDICATOR SYMBOL LETTER S
+const UChar32 kRisS = 0x1F1F8;
+} // namespace
+
+
+TEST(ForwardGraphemeBoundaryStatemachineTest, DoNothingCase)
+{
+    ForwardGraphemeBoundaryStateMachine machine;
+
+    EXPECT_EQ(0, machine.finalizeAndGetBoundaryOffset());
+    EXPECT_EQ(0, machine.finalizeAndGetBoundaryOffset());
+}
+
+TEST(ForwardGraphemeBoundaryStatemachineTest, PrecedingText)
+{
+    const std::vector<UChar32> kEmpty;
+    ForwardGraphemeBoundaryStateMachine machine;
+    // Preceding text should not affect the result except for flags.
+    // SOT + | + 'a' + 'a'
+    EXPECT_EQ("SRF", processSequenceForward(&machine, kEmpty, { 'a', 'a' }));
+    EXPECT_EQ(1, machine.finalizeAndGetBoundaryOffset());
+    // SOT + [U] + | + 'a' + 'a'
+    EXPECT_EQ("RRSRF", processSequenceForward(&machine,
+        { kRisU }, { 'a', 'a' }));
+    EXPECT_EQ(1, machine.finalizeAndGetBoundaryOffset());
+    // SOT + [U] + [S] + | + 'a' + 'a'
+    EXPECT_EQ("RRRRSRF", processSequenceForward(&machine,
+        { kRisU, kRisS }, { 'a', 'a' }));
+    EXPECT_EQ(1, machine.finalizeAndGetBoundaryOffset());
+
+    // 'a' + | + 'a' + 'a'
+    EXPECT_EQ("SRF", processSequenceForward(&machine, { 'a' }, { 'a', 'a' }));
+    EXPECT_EQ(1, machine.finalizeAndGetBoundaryOffset());
+    // 'a' + [U] + | + 'a' + 'a'
+    EXPECT_EQ("RRSRF", processSequenceForward(&machine,
+        { 'a', kRisU }, { 'a', 'a' }));
+    EXPECT_EQ(1, machine.finalizeAndGetBoundaryOffset());
+    // 'a' + [U] + [S] + | + 'a' + 'a'
+    EXPECT_EQ("RRRRSRF", processSequenceForward(&machine,
+        { 'a', kRisU, kRisS }, { 'a', 'a' }));
+    EXPECT_EQ(1, machine.finalizeAndGetBoundaryOffset());
+
+    // U+1F441 + | + 'a' + 'a'
+    EXPECT_EQ("RSRF", processSequenceForward(&machine,
+        { kEye }, { 'a', 'a' }));
+    EXPECT_EQ(1, machine.finalizeAndGetBoundaryOffset());
+    // U+1F441 + [U] + | + 'a' + 'a'
+    EXPECT_EQ("RRRSRF", processSequenceForward(&machine,
+        { kEye, kRisU }, { 'a', 'a' }));
+    EXPECT_EQ(1, machine.finalizeAndGetBoundaryOffset());
+    // U+1F441 + [U] + [S] + | + 'a' + 'a'
+    EXPECT_EQ("RRRRRSRF", processSequenceForward(&machine,
+        { kEye, kRisU, kRisS }, { 'a', 'a' }));
+    EXPECT_EQ(1, machine.finalizeAndGetBoundaryOffset());
+
+    // Broken surrogates in preceding text.
+
+    // [Lead] + | + 'a' + 'a'
+    EXPECT_EQ("SRF", processSequenceForward(&machine,
+        { kLead }, { 'a', 'a' }));
+    EXPECT_EQ(1, machine.finalizeAndGetBoundaryOffset());
+    // [Lead] + [U] + | + 'a' + 'a'
+    EXPECT_EQ("RRSRF", processSequenceForward(&machine,
+        { kLead, kRisU }, { 'a', 'a' }));
+    EXPECT_EQ(1, machine.finalizeAndGetBoundaryOffset());
+    // [Lead] + [U] + [S] + | + 'a' + 'a'
+    EXPECT_EQ("RRRRSRF", processSequenceForward(&machine,
+        { kLead, kRisU, kRisS }, { 'a', 'a' }));
+    EXPECT_EQ(1, machine.finalizeAndGetBoundaryOffset());
+
+    // 'a' + [Trail] + | + 'a' + 'a'
+    EXPECT_EQ("RSRF", processSequenceForward(&machine,
+        { 'a', kTrail }, { 'a', 'a' }));
+    EXPECT_EQ(1, machine.finalizeAndGetBoundaryOffset());
+    // 'a' + [Trail] + [U] + | + 'a' + 'a'
+    EXPECT_EQ("RRRSRF", processSequenceForward(&machine,
+        { 'a', kTrail, kRisU }, { 'a', 'a' }));
+    EXPECT_EQ(1, machine.finalizeAndGetBoundaryOffset());
+    // 'a' + [Trail] + [U] + [S] + | + 'a' + 'a'
+    EXPECT_EQ("RRRRRSRF", processSequenceForward(&machine,
+        { 'a', kTrail, kRisU, kRisS }, { 'a', 'a' }));
+    EXPECT_EQ(1, machine.finalizeAndGetBoundaryOffset());
+
+    // [Trail] + [Trail] + | + 'a' + 'a'
+    EXPECT_EQ("RSRF", processSequenceForward(&machine,
+        { kTrail, kTrail }, { 'a', 'a' }));
+    EXPECT_EQ(1, machine.finalizeAndGetBoundaryOffset());
+    // [Trail] + [Trail] + [U] + | + 'a' + 'a'
+    EXPECT_EQ("RRRSRF", processSequenceForward(&machine,
+        { kTrail, kTrail, kRisU }, { 'a', 'a' }));
+    EXPECT_EQ(1, machine.finalizeAndGetBoundaryOffset());
+    // [Trail] + [Trail] + [U] + [S] + | + 'a' + 'a'
+    EXPECT_EQ("RRRRRSRF", processSequenceForward(&machine,
+        { kTrail, kTrail, kRisU, kRisS }, { 'a', 'a' }));
+    EXPECT_EQ(1, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + [Trail] + | + 'a' + 'a'
+    EXPECT_EQ("RSRF", processSequenceForward(&machine,
+        { kTrail }, { 'a', 'a' }));
+    EXPECT_EQ(1, machine.finalizeAndGetBoundaryOffset());
+    // SOT + [Trail] + [U] + | + 'a' + 'a'
+    EXPECT_EQ("RRRSRF", processSequenceForward(&machine,
+        { kTrail, kRisU }, { 'a', 'a' }));
+    EXPECT_EQ(1, machine.finalizeAndGetBoundaryOffset());
+    // SOT + [Trail] + [U] + [S] + | + 'a' + 'a'
+    EXPECT_EQ("RRRRRSRF", processSequenceForward(&machine,
+        { kTrail, kRisU, kRisS }, { 'a', 'a' }));
+    EXPECT_EQ(1, machine.finalizeAndGetBoundaryOffset());
+}
+
+TEST(ForwardGraphemeBoundaryStatemachineTest, BrokenSurrogatePair)
+{
+    const std::vector<UChar32> kEmpty;
+    ForwardGraphemeBoundaryStateMachine machine;
+    // SOT + | + [Trail]
+    EXPECT_EQ("SF", processSequenceForward(&machine, kEmpty, { kTrail }));
+    EXPECT_EQ(1, machine.finalizeAndGetBoundaryOffset());
+    // SOT + | + [Lead] + 'a'
+    EXPECT_EQ("SRF", processSequenceForward(&machine, kEmpty, { kLead, 'a' }));
+    EXPECT_EQ(1, machine.finalizeAndGetBoundaryOffset());
+    // SOT + | + [Lead] + [Lead]
+    EXPECT_EQ("SRF", processSequenceForward(&machine, kEmpty,
+        { kLead, kLead }));
+    EXPECT_EQ(1, machine.finalizeAndGetBoundaryOffset());
+    // SOT + | + [Lead] + EOT
+    EXPECT_EQ("SR", processSequenceForward(&machine, kEmpty, { kLead }));
+    EXPECT_EQ(1, machine.finalizeAndGetBoundaryOffset());
+}
+
+TEST(ForwardGraphemeBoundaryStatemachineTest, BreakImmediately_BMP)
+{
+    const std::vector<UChar32> kEmpty;
+    ForwardGraphemeBoundaryStateMachine machine;
+
+    // SOT + | + 'a' + 'a'
+    EXPECT_EQ("SRF", processSequenceForward(&machine, kEmpty, { 'a', 'a' }));
+    EXPECT_EQ(1, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + 'a' + U+1F441
+    EXPECT_EQ("SRRF", processSequenceForward(&machine, kEmpty, { 'a', kEye }));
+    EXPECT_EQ(1, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + 'a' + EOT
+    EXPECT_EQ("SR", processSequenceForward(&machine, kEmpty, { 'a' }));
+    EXPECT_EQ(1, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + 'a' + [Trail]
+    EXPECT_EQ("SRF", processSequenceForward(&machine, kEmpty, { 'a', kTrail }));
+    EXPECT_EQ(1, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + 'a' + [Lead] + 'a'
+    EXPECT_EQ("SRRF", processSequenceForward(&machine, kEmpty,
+        { 'a', kLead, 'a' }));
+    EXPECT_EQ(1, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + 'a' + [Lead] + [Lead]
+    EXPECT_EQ("SRRF", processSequenceForward(&machine, kEmpty,
+        { 'a', kLead, kLead }));
+    EXPECT_EQ(1, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + 'a' + [Lead] + EOT
+    EXPECT_EQ("SRR", processSequenceForward(&machine, kEmpty, { 'a', kLead }));
+    EXPECT_EQ(1, machine.finalizeAndGetBoundaryOffset());
+}
+
+TEST(ForwardGraphemeBoundaryStatemachineTest, BreakImmediately_Supplementary)
+{
+    const std::vector<UChar32> kEmpty;
+    ForwardGraphemeBoundaryStateMachine machine;
+
+    // SOT + | + U+1F441 + 'a'
+    EXPECT_EQ("SRRF", processSequenceForward(&machine, kEmpty, { kEye, 'a' }));
+    EXPECT_EQ(2, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + U+1F441 + U+1F441
+    EXPECT_EQ("SRRRF", processSequenceForward(&machine, kEmpty,
+        { kEye, kEye }));
+    EXPECT_EQ(2, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + U+1F441 + EOT
+    EXPECT_EQ("SRR", processSequenceForward(&machine, kEmpty, { kEye }));
+    EXPECT_EQ(2, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + U+1F441 + [Trail]
+    EXPECT_EQ("SRRF", processSequenceForward(&machine, kEmpty,
+        { kEye, kTrail }));
+    EXPECT_EQ(2, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + U+1F441 + [Lead] + 'a'
+    EXPECT_EQ("SRRRF", processSequenceForward(&machine, kEmpty,
+        { kEye, kLead, 'a' }));
+    EXPECT_EQ(2, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + U+1F441 + [Lead] + [Lead]
+    EXPECT_EQ("SRRRF", processSequenceForward(&machine, kEmpty,
+        { kEye, kLead, kLead }));
+    EXPECT_EQ(2, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + U+1F441 + [Lead] + EOT
+    EXPECT_EQ("SRRR", processSequenceForward(&machine, kEmpty,
+        { kEye, kLead }));
+    EXPECT_EQ(2, machine.finalizeAndGetBoundaryOffset());
+}
+
+TEST(ForwardGraphemeBoundaryStatemachineTest, NotBreakImmediatelyAfter_BMP_BMP)
+{
+    const std::vector<UChar32> kEmpty;
+    ForwardGraphemeBoundaryStateMachine machine;
+
+    // SOT + | + U+231A + U+FE0F + 'a'
+    EXPECT_EQ("SRRF", processSequenceForward(&machine, kEmpty,
+        { kWatch, kVS16, 'a' }));
+    EXPECT_EQ(2, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + U+231A + U+FE0F + U+1F441
+    EXPECT_EQ("SRRRF", processSequenceForward(&machine, kEmpty,
+        { kWatch, kVS16, kEye }));
+    EXPECT_EQ(2, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + U+231A + U+FE0F + EOT
+    EXPECT_EQ("SRR", processSequenceForward(&machine, kEmpty,
+        { kWatch, kVS16 }));
+    EXPECT_EQ(2, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + U+231A + U+FE0F + [Trail]
+    EXPECT_EQ("SRRF", processSequenceForward(&machine, kEmpty,
+        { kWatch, kVS16, kTrail }));
+    EXPECT_EQ(2, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + U+231A + U+FE0F + [Lead] + 'a'
+    EXPECT_EQ("SRRRF", processSequenceForward(&machine, kEmpty,
+        { kWatch, kVS16, kLead, 'a' }));
+    EXPECT_EQ(2, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + U+231A + U+FE0F + [Lead] + [Lead]
+    EXPECT_EQ("SRRRF", processSequenceForward(&machine, kEmpty,
+        { kWatch, kVS16, kLead, kLead }));
+    EXPECT_EQ(2, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + U+231A + U+FE0F + [Lead] + EOT
+    EXPECT_EQ("SRRR", processSequenceForward(&machine, kEmpty,
+        { kWatch, kVS16, kLead }));
+    EXPECT_EQ(2, machine.finalizeAndGetBoundaryOffset());
+}
+
+TEST(ForwardGraphemeBoundaryStatemachineTest,
+    NotBreakImmediatelyAfter_Supplementary_BMP)
+{
+    const std::vector<UChar32> kEmpty;
+    ForwardGraphemeBoundaryStateMachine machine;
+
+    // SOT + | + U+1F441 + U+FE0F + 'a'
+    EXPECT_EQ("SRRRF", processSequenceForward(&machine, kEmpty,
+        { kEye, kVS16, 'a' }));
+    EXPECT_EQ(3, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + U+1F441 + U+FE0F + U+1F441
+    EXPECT_EQ("SRRRRF", processSequenceForward(&machine, kEmpty,
+        { kEye, kVS16, kEye }));
+    EXPECT_EQ(3, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + U+1F441 + U+FE0F + EOT
+    EXPECT_EQ("SRRR", processSequenceForward(&machine, kEmpty,
+        { kEye, kVS16 }));
+    EXPECT_EQ(3, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + U+1F441 + U+FE0F + [Trail]
+    EXPECT_EQ("SRRRF", processSequenceForward(&machine, kEmpty,
+        { kEye, kVS16, kTrail }));
+    EXPECT_EQ(3, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + U+1F441 + U+FE0F + [Lead] + 'a'
+    EXPECT_EQ("SRRRRF", processSequenceForward(&machine, kEmpty,
+        { kEye, kVS16, kLead, 'a' }));
+    EXPECT_EQ(3, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + U+1F441 + U+FE0F + [Lead] + [Lead]
+    EXPECT_EQ("SRRRRF", processSequenceForward(&machine, kEmpty,
+        { kEye, kVS16, kLead, kLead }));
+    EXPECT_EQ(3, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + U+1F441 + U+FE0F + [Lead] + EOT
+    EXPECT_EQ("SRRRR", processSequenceForward(&machine, kEmpty,
+        { kEye, kVS16, kLead }));
+    EXPECT_EQ(3, machine.finalizeAndGetBoundaryOffset());
+}
+
+TEST(ForwardGraphemeBoundaryStatemachineTest,
+    NotBreakImmediatelyAfter_BMP_Supplementary)
+{
+    const std::vector<UChar32> kEmpty;
+    ForwardGraphemeBoundaryStateMachine machine;
+
+    // SOT + | + U+845B + U+E0100 + 'a'
+    EXPECT_EQ("SRRRF", processSequenceForward(&machine, kEmpty,
+        { kHanBMP, kVS17, 'a' }));
+    EXPECT_EQ(3, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + U+845B + U+E0100 + U+1F441
+    EXPECT_EQ("SRRRRF", processSequenceForward(&machine, kEmpty,
+        { kHanBMP, kVS17, kEye }));
+    EXPECT_EQ(3, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + U+845B + U+E0100 + EOT
+    EXPECT_EQ("SRRR", processSequenceForward(&machine, kEmpty,
+        { kHanBMP, kVS17 }));
+    EXPECT_EQ(3, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + U+845B + U+E0100 + [Trail]
+    EXPECT_EQ("SRRRF", processSequenceForward(&machine, kEmpty,
+        { kHanBMP, kVS17, kTrail }));
+    EXPECT_EQ(3, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + U+845B + U+E0100 + [Lead] + 'a'
+    EXPECT_EQ("SRRRRF", processSequenceForward(&machine, kEmpty,
+        { kHanBMP, kVS17, kLead, 'a' }));
+    EXPECT_EQ(3, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + U+845B + U+E0100 + [Lead] + [Lead]
+    EXPECT_EQ("SRRRRF", processSequenceForward(&machine, kEmpty,
+        { kHanBMP, kVS17, kLead, kLead }));
+    EXPECT_EQ(3, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + U+845B + U+E0100 + [Lead] + EOT
+    EXPECT_EQ("SRRRR", processSequenceForward(&machine, kEmpty,
+        { kHanBMP, kVS17, kLead }));
+    EXPECT_EQ(3, machine.finalizeAndGetBoundaryOffset());
+}
+
+TEST(ForwardGraphemeBoundaryStatemachineTest,
+    NotBreakImmediatelyAfter_Supplementary_Supplementary)
+{
+    const std::vector<UChar32> kEmpty;
+    ForwardGraphemeBoundaryStateMachine machine;
+
+    // SOT + | + U+20000 + U+E0100 + 'a'
+    EXPECT_EQ("SRRRRF", processSequenceForward(&machine, kEmpty,
+        { kHanSIP, kVS17, 'a' }));
+    EXPECT_EQ(4, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + U+20000 + U+E0100 + U+1F441
+    EXPECT_EQ("SRRRRRF", processSequenceForward(&machine, kEmpty,
+        { kHanSIP, kVS17, kEye }));
+    EXPECT_EQ(4, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + U+20000 + U+E0100 + EOT
+    EXPECT_EQ("SRRRR", processSequenceForward(&machine, kEmpty,
+        { kHanSIP, kVS17 }));
+    EXPECT_EQ(4, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + U+20000 + U+E0100 + [Trail]
+    EXPECT_EQ("SRRRRF", processSequenceForward(&machine, kEmpty,
+        { kHanSIP, kVS17, kTrail }));
+    EXPECT_EQ(4, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + U+20000 + U+E0100 + [Lead] + 'a'
+    EXPECT_EQ("SRRRRRF", processSequenceForward(&machine, kEmpty,
+        { kHanSIP, kVS17, kLead, 'a' }));
+    EXPECT_EQ(4, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + U+20000 + U+E0100 + [Lead] + [Lead]
+    EXPECT_EQ("SRRRRRF", processSequenceForward(&machine, kEmpty,
+        { kHanSIP, kVS17, kLead, kLead }));
+    EXPECT_EQ(4, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + U+20000 + U+E0100 + [Lead] + EOT
+    EXPECT_EQ("SRRRRR", processSequenceForward(&machine, kEmpty,
+        { kHanSIP, kVS17, kLead }));
+    EXPECT_EQ(4, machine.finalizeAndGetBoundaryOffset());
+}
+
+TEST(ForwardGraphemeBoundaryStatemachineTest, MuchLongerCase)
+{
+    const std::vector<UChar32> kEmpty;
+    ForwardGraphemeBoundaryStateMachine machine;
+
+    const UChar32 kMan = WTF::Unicode::manCharacter;
+    const UChar32 kZwj = WTF::Unicode::zeroWidthJoinerCharacter;
+    const UChar32 kHeart = WTF::Unicode::heavyBlackHeartCharacter;
+    const UChar32 kKiss = WTF::Unicode::kissMarkCharacter;
+
+    // U+1F468 U+200D U+2764 U+FE0F U+200D U+1F48B U+200D U+1F468 is a valid ZWJ
+    // emoji sequence.
+    // SOT + | + ZWJ Emoji Sequence + 'a'
+    EXPECT_EQ("SRRRRRRRRRRRF", processSequenceForward(&machine, kEmpty,
+        { kMan, kZwj, kHeart, kVS16, kZwj, kKiss, kZwj, kMan, 'a' }));
+    EXPECT_EQ(11, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + ZWJ Emoji Sequence + U+1F441
+    EXPECT_EQ("SRRRRRRRRRRRRF", processSequenceForward(&machine, kEmpty,
+        { kMan, kZwj, kHeart, kVS16, kZwj, kKiss, kZwj, kMan, kEye }));
+    EXPECT_EQ(11, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + ZWJ Emoji Sequence + EOT
+    EXPECT_EQ("SRRRRRRRRRRR", processSequenceForward(&machine, kEmpty,
+        { kMan, kZwj, kHeart, kVS16, kZwj, kKiss, kZwj, kMan }));
+    EXPECT_EQ(11, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + ZWJ Emoji Sequence + [Trail]
+    EXPECT_EQ("SRRRRRRRRRRRF", processSequenceForward(&machine, kEmpty,
+        { kMan, kZwj, kHeart, kVS16, kZwj, kKiss, kZwj, kMan, kTrail }));
+    EXPECT_EQ(11, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + ZWJ Emoji Sequence + [Lead] + 'a'
+    EXPECT_EQ("SRRRRRRRRRRRRF", processSequenceForward(&machine, kEmpty,
+        { kMan, kZwj, kHeart, kVS16, kZwj, kKiss, kZwj, kMan, kLead, 'a' }));
+    EXPECT_EQ(11, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + ZWJ Emoji Sequence + [Lead] + [Lead]
+    EXPECT_EQ("SRRRRRRRRRRRRF", processSequenceForward(&machine, kEmpty,
+        { kMan, kZwj, kHeart, kVS16, kZwj, kKiss, kZwj, kMan, kLead, kLead }));
+    EXPECT_EQ(11, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + | + ZWJ Emoji Sequence + [Lead] + EOT
+    EXPECT_EQ("SRRRRRRRRRRRR", processSequenceForward(&machine, kEmpty,
+        { kMan, kZwj, kHeart, kVS16, kZwj, kKiss, kZwj, kMan, kLead }));
+    EXPECT_EQ(11, machine.finalizeAndGetBoundaryOffset());
+
+    // Preceding text should not affect the result except for flags.
+    // 'a' + | + ZWJ Emoji Sequence + [Lead] + EOT
+    EXPECT_EQ("SRRRRRRRRRRRF", processSequenceForward(&machine,
+        { 'a' },
+        { kMan, kZwj, kHeart, kVS16, kZwj, kKiss, kZwj, kMan, 'a' }));
+    EXPECT_EQ(11, machine.finalizeAndGetBoundaryOffset());
+
+    // U+1F441 + | + ZWJ Emoji Sequence + [Lead] + EOT
+    EXPECT_EQ("RSRRRRRRRRRRRF", processSequenceForward(&machine,
+        { kEye },
+        { kMan, kZwj, kHeart, kVS16, kZwj, kKiss, kZwj, kMan, 'a' }));
+    EXPECT_EQ(11, machine.finalizeAndGetBoundaryOffset());
+
+    // [Lead] + | + ZWJ Emoji Sequence + [Lead] + EOT
+    EXPECT_EQ("SRRRRRRRRRRRF", processSequenceForward(&machine,
+        { kLead },
+        { kMan, kZwj, kHeart, kVS16, kZwj, kKiss, kZwj, kMan, 'a' }));
+    EXPECT_EQ(11, machine.finalizeAndGetBoundaryOffset());
+
+    // 'a' + [Trail] + | + ZWJ Emoji Sequence + [Lead] + EOT
+    EXPECT_EQ("RSRRRRRRRRRRRF", processSequenceForward(&machine,
+        { 'a', kTrail },
+        { kMan, kZwj, kHeart, kVS16, kZwj, kKiss, kZwj, kMan, 'a' }));
+    EXPECT_EQ(11, machine.finalizeAndGetBoundaryOffset());
+
+    // [Trail] + [Trail] + | + ZWJ Emoji Sequence + [Lead] + EOT
+    EXPECT_EQ("RSRRRRRRRRRRRF", processSequenceForward(&machine,
+        { kTrail, kTrail },
+        { kMan, kZwj, kHeart, kVS16, kZwj, kKiss, kZwj, kMan, 'a' }));
+    EXPECT_EQ(11, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + [Trail] + | + ZWJ Emoji Sequence + [Lead] + EOT
+    EXPECT_EQ("RSRRRRRRRRRRRF", processSequenceForward(&machine,
+        { kTrail },
+        { kMan, kZwj, kHeart, kVS16, kZwj, kKiss, kZwj, kMan, 'a' }));
+    EXPECT_EQ(11, machine.finalizeAndGetBoundaryOffset());
+
+    // 'a' + [U] + | + ZWJ Emoji Sequence + [Lead] + EOT
+    EXPECT_EQ("RRSRRRRRRRRRRRF", processSequenceForward(&machine,
+        { 'a', kRisU },
+        { kMan, kZwj, kHeart, kVS16, kZwj, kKiss, kZwj, kMan, 'a' }));
+    EXPECT_EQ(11, machine.finalizeAndGetBoundaryOffset());
+
+    // 'a' + [U] + [S] + | + ZWJ Emoji Sequence + [Lead] + EOT
+    EXPECT_EQ("RRRRSRRRRRRRRRRRF", processSequenceForward(&machine,
+        { 'a', kRisU, kRisS },
+        { kMan, kZwj, kHeart, kVS16, kZwj, kKiss, kZwj, kMan, 'a' }));
+    EXPECT_EQ(11, machine.finalizeAndGetBoundaryOffset());
+
+}
+
+TEST(ForwardGraphemeBoundaryStatemachineTest, singleFlags)
+{
+    const std::vector<UChar32> kEmpty;
+    ForwardGraphemeBoundaryStateMachine machine;
+
+    // SOT + | + [U] + [S]
+    EXPECT_EQ("SRRRF", processSequenceForward(&machine,
+        kEmpty, { kRisU, kRisS }));
+    EXPECT_EQ(4, machine.finalizeAndGetBoundaryOffset());
+
+    // 'a' + | + [U] + [S]
+    EXPECT_EQ("SRRRF", processSequenceForward(&machine,
+        { 'a' }, { kRisU, kRisS }));
+    EXPECT_EQ(4, machine.finalizeAndGetBoundaryOffset());
+
+    // U+1F441 + | + [U] + [S]
+    EXPECT_EQ("RSRRRF", processSequenceForward(&machine,
+        { kEye }, { kRisU, kRisS }));
+    EXPECT_EQ(4, machine.finalizeAndGetBoundaryOffset());
+
+    // [Lead] + | + [U] + [S]
+    EXPECT_EQ("SRRRF", processSequenceForward(&machine,
+        { kLead }, { kRisU, kRisS }));
+    EXPECT_EQ(4, machine.finalizeAndGetBoundaryOffset());
+
+    // 'a' + [Trail] + | + [U] + [S]
+    EXPECT_EQ("RSRRRF", processSequenceForward(&machine,
+        { 'a', kTrail }, { kRisU, kRisS }));
+    EXPECT_EQ(4, machine.finalizeAndGetBoundaryOffset());
+
+    // [Trail] + [Trail] + | + [U] + [S]
+    EXPECT_EQ("RSRRRF", processSequenceForward(&machine,
+        { kTrail, kTrail }, { kRisU, kRisS }));
+    EXPECT_EQ(4, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + [Trail] + | + [U] + [S]
+    EXPECT_EQ("RSRRRF", processSequenceForward(&machine,
+        { kTrail }, { kRisU, kRisS }));
+    EXPECT_EQ(4, machine.finalizeAndGetBoundaryOffset());
+}
+
+TEST(ForwardGraphemeBoundaryStatemachineTest, twoFlags)
+{
+    ForwardGraphemeBoundaryStateMachine machine;
+
+    // SOT + [U] + [S] + | + [U] + [S]
+    EXPECT_EQ("RRRRSRRRF", processSequenceForward(&machine,
+        { kRisU, kRisS }, { kRisU, kRisS }));
+    EXPECT_EQ(4, machine.finalizeAndGetBoundaryOffset());
+
+    // 'a' + [U] + [S] + | + [U] + [S]
+    EXPECT_EQ("RRRRSRRRF", processSequenceForward(&machine,
+        { 'a', kRisU, kRisS }, { kRisU, kRisS }));
+    EXPECT_EQ(4, machine.finalizeAndGetBoundaryOffset());
+
+    // U+1F441 + [U] + [S] + | + [U] + [S]
+    EXPECT_EQ("RRRRRSRRRF", processSequenceForward(&machine,
+        { kEye, kRisU, kRisS }, { kRisU, kRisS }));
+    EXPECT_EQ(4, machine.finalizeAndGetBoundaryOffset());
+
+    // [Lead] + [U] + [S] + | + [U] + [S]
+    EXPECT_EQ("RRRRSRRRF", processSequenceForward(&machine,
+        { kLead, kRisU, kRisS }, { kRisU, kRisS }));
+    EXPECT_EQ(4, machine.finalizeAndGetBoundaryOffset());
+
+    // 'a' + [Trail] + [U] + [S] + | + [U] + [S]
+    EXPECT_EQ("RRRRRSRRRF", processSequenceForward(&machine,
+        { 'a', kTrail, kRisU, kRisS }, { kRisU, kRisS }));
+    EXPECT_EQ(4, machine.finalizeAndGetBoundaryOffset());
+
+    // [Trail] + [Trail] + [U] + [S] + | + [U] + [S]
+    EXPECT_EQ("RRRRRSRRRF", processSequenceForward(&machine,
+        { kTrail, kTrail, kRisU, kRisS }, { kRisU, kRisS }));
+    EXPECT_EQ(4, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + [Trail] + [U] + [S] + | + [U] + [S]
+    EXPECT_EQ("RRRRRSRRRF", processSequenceForward(&machine,
+        { kTrail, kRisU, kRisS }, { kRisU, kRisS }));
+    EXPECT_EQ(4, machine.finalizeAndGetBoundaryOffset());
+}
+
+TEST(ForwardGraphemeBoundaryStatemachineTest, oddNumberedFlags)
+{
+    ForwardGraphemeBoundaryStateMachine machine;
+
+    // SOT + [U] + | + [S] + [S]
+    EXPECT_EQ("RRSRRRF", processSequenceForward(&machine,
+        { kRisU }, { kRisS, kRisU }));
+    EXPECT_EQ(2, machine.finalizeAndGetBoundaryOffset());
+
+    // 'a' + [U] + | + [S] + [S]
+    EXPECT_EQ("RRSRRRF", processSequenceForward(&machine,
+        { 'a', kRisU }, { kRisS, kRisU }));
+    EXPECT_EQ(2, machine.finalizeAndGetBoundaryOffset());
+
+    // U+1F441 + [U] + | + [S] + [S]
+    EXPECT_EQ("RRRSRRRF", processSequenceForward(&machine,
+        { kEye, kRisU }, { kRisS, kRisU }));
+    EXPECT_EQ(2, machine.finalizeAndGetBoundaryOffset());
+
+    // [Lead] + [U] + | + [S] + [S]
+    EXPECT_EQ("RRSRRRF", processSequenceForward(&machine,
+        { kLead, kRisU }, { kRisS, kRisU }));
+    EXPECT_EQ(2, machine.finalizeAndGetBoundaryOffset());
+
+    // 'a' + [Trail] + [U] + | + [S] + [S]
+    EXPECT_EQ("RRRSRRRF", processSequenceForward(&machine,
+        { 'a', kTrail, kRisU }, { kRisS, kRisU }));
+    EXPECT_EQ(2, machine.finalizeAndGetBoundaryOffset());
+
+    // [Trail] + [Trail] + [U] + | + [S] + [S]
+    EXPECT_EQ("RRRSRRRF", processSequenceForward(&machine,
+        { kTrail, kTrail, kRisU }, { kRisS, kRisU }));
+    EXPECT_EQ(2, machine.finalizeAndGetBoundaryOffset());
+
+    // SOT + [Trail] + [U] + | + [S] + [S]
+    EXPECT_EQ("RRRSRRRF", processSequenceForward(&machine,
+        { kTrail, kRisU }, { kRisS, kRisU }));
+    EXPECT_EQ(2, machine.finalizeAndGetBoundaryOffset());
+}
+
+} // namespace blink
diff --git a/third_party/WebKit/Source/core/editing/state_machines/StateMachineTestUtil.cpp b/third_party/WebKit/Source/core/editing/state_machines/StateMachineTestUtil.cpp
index a2062f9..c009346 100644
--- a/third_party/WebKit/Source/core/editing/state_machines/StateMachineTestUtil.cpp
+++ b/third_party/WebKit/Source/core/editing/state_machines/StateMachineTestUtil.cpp
@@ -5,6 +5,7 @@
 #include "core/editing/state_machines/StateMachineTestUtil.h"
 
 #include "core/editing/state_machines/BackwardGraphemeBoundaryStateMachine.h"
+#include "core/editing/state_machines/ForwardGraphemeBoundaryStateMachine.h"
 #include "core/editing/state_machines/TextSegmentationMachineState.h"
 #include "wtf/Assertions.h"
 #include <algorithm>
@@ -64,7 +65,8 @@
             break;
         }
     }
-    if (state == TextSegmentationMachineState::NeedMoreCodeUnit) {
+    if (preceding.empty()
+        || state == TextSegmentationMachineState::NeedMoreCodeUnit) {
         state = machine->tellEndOfPrecedingText();
         out += MachineStateToChar(state);
     }
@@ -95,9 +97,21 @@
 {
     const std::string& out =
         processSequence(machine, preceding, std::vector<UChar32>());
-    DCHECK_EQ(machine->finalizeAndGetBoundaryOffset(),
-        machine->finalizeAndGetBoundaryOffset())
-        << "finalizeAndGetBoundaryOffset should return fixed values.";
+    if (machine->finalizeAndGetBoundaryOffset()
+        != machine->finalizeAndGetBoundaryOffset())
+        return "State machine changes final offset after finished.";
+    return out;
+}
+
+std::string processSequenceForward(
+    ForwardGraphemeBoundaryStateMachine* machine,
+    const std::vector<UChar32>& preceding,
+    const std::vector<UChar32>& following)
+{
+    const std::string& out = processSequence(machine, preceding, following);
+    if (machine->finalizeAndGetBoundaryOffset()
+        != machine->finalizeAndGetBoundaryOffset())
+        return "State machine changes final offset after finished.";
     return out;
 }
 
diff --git a/third_party/WebKit/Source/core/editing/state_machines/StateMachineTestUtil.h b/third_party/WebKit/Source/core/editing/state_machines/StateMachineTestUtil.h
index f3f2060..8ad1d34 100644
--- a/third_party/WebKit/Source/core/editing/state_machines/StateMachineTestUtil.h
+++ b/third_party/WebKit/Source/core/editing/state_machines/StateMachineTestUtil.h
@@ -10,6 +10,7 @@
 namespace blink {
 
 class BackwardGraphemeBoundaryStateMachine;
+class ForwardGraphemeBoundaryStateMachine;
 
 // Processes the |machine| with preceding/following code points.
 // The result string represents the output sequence of the state machine.
@@ -26,4 +27,8 @@
     BackwardGraphemeBoundaryStateMachine*,
     const std::vector<UChar32>& preceding);
 
+std::string processSequenceForward(
+    ForwardGraphemeBoundaryStateMachine*,
+    const std::vector<UChar32>& preceding,
+    const std::vector<UChar32>& following);
 } // namespace blink
diff --git a/third_party/WebKit/Source/core/editing/state_machines/StateMachineUtil.cpp b/third_party/WebKit/Source/core/editing/state_machines/StateMachineUtil.cpp
index fe3a4d0..2889d75 100644
--- a/third_party/WebKit/Source/core/editing/state_machines/StateMachineUtil.cpp
+++ b/third_party/WebKit/Source/core/editing/state_machines/StateMachineUtil.cpp
@@ -4,7 +4,7 @@
 
 #include "core/editing/state_machines/StateMachineUtil.h"
 
-#include "platform/fonts/Character.h"
+#include "platform/text/Character.h"
 #include "wtf/Assertions.h"
 #include "wtf/text/CharacterNames.h"
 #include "wtf/text/Unicode.h"
diff --git a/third_party/WebKit/Source/core/events/EventPath.cpp b/third_party/WebKit/Source/core/events/EventPath.cpp
index 085d0689a..901088c 100644
--- a/third_party/WebKit/Source/core/events/EventPath.cpp
+++ b/third_party/WebKit/Source/core/events/EventPath.cpp
@@ -268,7 +268,7 @@
         return;
     if (target.document() != relatedNode->document())
         return;
-    if (!target.inDocument() || !relatedNode->inDocument())
+    if (!target.inShadowIncludingDocument() || !relatedNode->inShadowIncludingDocument())
         return;
 
     RelatedTargetMap relatedNodeMap;
diff --git a/third_party/WebKit/Source/core/events/EventTarget.cpp b/third_party/WebKit/Source/core/events/EventTarget.cpp
index 83e7ad4..75dd0477 100644
--- a/third_party/WebKit/Source/core/events/EventTarget.cpp
+++ b/third_party/WebKit/Source/core/events/EventTarget.cpp
@@ -439,7 +439,7 @@
 
         event->setHandlingPassive(registeredListener.passive);
 
-        InspectorInstrumentationCookie cookie = InspectorInstrumentation::willHandleEvent(this, event, registeredListener.listener.get(), registeredListener.useCapture);
+        InspectorInstrumentation::willHandleEvent(this, event, registeredListener.listener.get(), registeredListener.useCapture);
 
         // To match Mozilla, the AT_TARGET phase fires both capturing and bubbling
         // event listeners, even though that violates some versions of the DOM spec.
@@ -447,8 +447,6 @@
         event->setHandlingPassive(false);
 
         RELEASE_ASSERT(i <= size);
-
-        InspectorInstrumentation::didHandleEvent(cookie);
     }
     d->firingEventIterators->removeLast();
 }
diff --git a/third_party/WebKit/Source/core/fetch/CrossOriginAccessControl.cpp b/third_party/WebKit/Source/core/fetch/CrossOriginAccessControl.cpp
index 672aebb6..7d3f7a5f 100644
--- a/third_party/WebKit/Source/core/fetch/CrossOriginAccessControl.cpp
+++ b/third_party/WebKit/Source/core/fetch/CrossOriginAccessControl.cpp
@@ -94,6 +94,13 @@
                 // Access-Control-Request-Headers header.
                 continue;
             }
+            if (equalIgnoringCase(header.key, "save-data")) {
+                // As a short-term fix, exclude Save-Data from
+                // Access-Control-Request-Headers header.
+                // TODO(rajendrant): crbug.com/601092 Longer-term all simple
+                // headers should be excluded as well.
+                continue;
+            }
             headers.append(header.key.lower());
         }
         std::sort(headers.begin(), headers.end(), WTF::codePointCompareLessThan);
diff --git a/third_party/WebKit/Source/core/fetch/RawResource.cpp b/third_party/WebKit/Source/core/fetch/RawResource.cpp
index 3925095c..4812927 100644
--- a/third_party/WebKit/Source/core/fetch/RawResource.cpp
+++ b/third_party/WebKit/Source/core/fetch/RawResource.cpp
@@ -133,6 +133,14 @@
         c->redirectReceived(this, newRequest, redirectResponse);
 }
 
+void RawResource::willNotFollowRedirect()
+{
+    RawPtr<RawResource> protect(this);
+    ResourceClientWalker<RawResourceClient> w(m_clients);
+    while (RawResourceClient* c = w.next())
+        c->redirectBlocked();
+}
+
 void RawResource::responseReceived(const ResourceResponse& response, PassOwnPtr<WebDataConsumerHandle> handle)
 {
     bool isSuccessfulRevalidation = isCacheValidator() && response.httpStatusCode() == 304;
diff --git a/third_party/WebKit/Source/core/fetch/RawResource.h b/third_party/WebKit/Source/core/fetch/RawResource.h
index 5935820..46f8cc0 100644
--- a/third_party/WebKit/Source/core/fetch/RawResource.h
+++ b/third_party/WebKit/Source/core/fetch/RawResource.h
@@ -80,6 +80,7 @@
     bool shouldIgnoreHTTPStatusCodeErrors() const override { return !isLinkPreload(); }
 
     void willFollowRedirect(ResourceRequest&, const ResourceResponse&) override;
+    void willNotFollowRedirect() override;
     void responseReceived(const ResourceResponse&, PassOwnPtr<WebDataConsumerHandle>) override;
     void setSerializedCachedMetadata(const char*, size_t) override;
     void didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent) override;
@@ -111,6 +112,7 @@
     virtual void setSerializedCachedMetadata(Resource*, const char*, size_t) { }
     virtual void dataReceived(Resource*, const char* /* data */, size_t /* length */) { }
     virtual void redirectReceived(Resource*, ResourceRequest&, const ResourceResponse&) { }
+    virtual void redirectBlocked() {}
     virtual void dataDownloaded(Resource*, int) { }
     virtual void didReceiveResourceTiming(Resource*, const ResourceTimingInfo&) { }
 };
diff --git a/third_party/WebKit/Source/core/fetch/Resource.h b/third_party/WebKit/Source/core/fetch/Resource.h
index c216902..e532c1a 100644
--- a/third_party/WebKit/Source/core/fetch/Resource.h
+++ b/third_party/WebKit/Source/core/fetch/Resource.h
@@ -180,6 +180,10 @@
 
     virtual void willFollowRedirect(ResourceRequest&, const ResourceResponse&);
 
+    // Called when a redirect response was received but a decision has
+    // already been made to not follow it.
+    virtual void willNotFollowRedirect() {}
+
     virtual void responseReceived(const ResourceResponse&, PassOwnPtr<WebDataConsumerHandle>);
     void setResponse(const ResourceResponse& response) { m_response = response; }
     const ResourceResponse& response() const { return m_response; }
diff --git a/third_party/WebKit/Source/core/fetch/ResourceLoader.cpp b/third_party/WebKit/Source/core/fetch/ResourceLoader.cpp
index 7f4bdfeee..048e101 100644
--- a/third_party/WebKit/Source/core/fetch/ResourceLoader.cpp
+++ b/third_party/WebKit/Source/core/fetch/ResourceLoader.cpp
@@ -215,10 +215,12 @@
     const ResourceResponse& redirectResponse(passedRedirectResponse.toResourceResponse());
     newRequest.setFollowedRedirect(true);
 
-    if (m_fetcher->willFollowRedirect(m_resource.get(), newRequest, redirectResponse))
+    if (m_fetcher->willFollowRedirect(m_resource.get(), newRequest, redirectResponse)) {
         m_resource->willFollowRedirect(newRequest, redirectResponse);
-    else
+    } else {
+        m_resource->willNotFollowRedirect();
         cancel(ResourceError::cancelledDueToAccessCheckError(newRequest.url()));
+    }
 }
 
 void ResourceLoader::didReceiveCachedMetadata(WebURLLoader*, const char* data, int length)
diff --git a/third_party/WebKit/Source/core/frame/DOMTimer.cpp b/third_party/WebKit/Source/core/frame/DOMTimer.cpp
index c1906114..6966ace 100644
--- a/third_party/WebKit/Source/core/frame/DOMTimer.cpp
+++ b/third_party/WebKit/Source/core/frame/DOMTimer.cpp
@@ -55,7 +55,7 @@
 {
     int timeoutID = context->timers()->installNewTimeout(context, action, timeout, singleShot);
     TRACE_EVENT_INSTANT1("devtools.timeline", "TimerInstall", TRACE_EVENT_SCOPE_THREAD, "data", InspectorTimerInstallEvent::data(context, timeoutID, timeout, singleShot));
-    InspectorInstrumentation::didInstallTimer(context, timeoutID, timeout, singleShot);
+    InspectorInstrumentation::allowNativeBreakpoint(context, "setTimer", true);
     return timeoutID;
 }
 
@@ -63,7 +63,7 @@
 {
     context->timers()->removeTimeoutByID(timeoutID);
     TRACE_EVENT_INSTANT1("devtools.timeline", "TimerRemove", TRACE_EVENT_SCOPE_THREAD, "data", InspectorTimerRemoveEvent::data(context, timeoutID));
-    InspectorInstrumentation::didRemoveTimer(context, timeoutID);
+    InspectorInstrumentation::allowNativeBreakpoint(context, "clearTimer", true);
 }
 
 DOMTimer::DOMTimer(ExecutionContext* context, ScheduledAction* action, int interval, bool singleShot, int timeoutID)
@@ -108,7 +108,7 @@
     UserGestureIndicator gestureIndicator(m_userGestureToken.release());
 
     TRACE_EVENT1("devtools.timeline", "TimerFire", "data", InspectorTimerFireEvent::data(context, m_timeoutID));
-    InspectorInstrumentationCookie cookie = InspectorInstrumentation::willFireTimer(context, m_timeoutID);
+    InspectorInstrumentation::allowNativeBreakpoint(context, "timerFired", false);
     InspectorInstrumentation::AsyncTask asyncTask(context, this);
 
     // Simple case for non-one-shot timers.
@@ -121,9 +121,6 @@
 
         // No access to member variables after this point, it can delete the timer.
         m_action->execute(context);
-
-        InspectorInstrumentation::didFireTimer(cookie);
-
         return;
     }
 
@@ -134,7 +131,6 @@
 
     action->execute(context);
 
-    InspectorInstrumentation::didFireTimer(cookie);
     TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "UpdateCounters", TRACE_EVENT_SCOPE_THREAD, "data", InspectorUpdateCountersEvent::data());
 
     // ExecutionContext might be already gone when we executed action->execute().
diff --git a/third_party/WebKit/Source/core/frame/DOMWindow.cpp b/third_party/WebKit/Source/core/frame/DOMWindow.cpp
index 8255c209..084b65e 100644
--- a/third_party/WebKit/Source/core/frame/DOMWindow.cpp
+++ b/third_party/WebKit/Source/core/frame/DOMWindow.cpp
@@ -332,7 +332,7 @@
     if (!frame()->shouldClose())
         return;
 
-    InspectorInstrumentation::willCloseWindow(context);
+    InspectorInstrumentation::allowNativeBreakpoint(context, "close", true);
 
     page->chromeClient().closeWindowSoon();
 
diff --git a/third_party/WebKit/Source/core/frame/DOMWindowProperty.cpp b/third_party/WebKit/Source/core/frame/DOMWindowProperty.cpp
index 3bbb5cb..6fc921d 100644
--- a/third_party/WebKit/Source/core/frame/DOMWindowProperty.cpp
+++ b/third_party/WebKit/Source/core/frame/DOMWindowProperty.cpp
@@ -33,9 +33,6 @@
 
 DOMWindowProperty::DOMWindowProperty(LocalFrame* frame)
     : m_frame(frame)
-#if !ENABLE(OILPAN)
-    , m_associatedDOMWindow(nullptr)
-#endif
 {
     // FIXME: For now it *is* acceptable for a DOMWindowProperty to be created with a null frame.
     // See fast/dom/navigator-detached-no-crash.html for the recipe.
@@ -43,38 +40,16 @@
     if (m_frame) {
         // FIXME: Need to figure out what to do with DOMWindowProperties on
         // remote DOM windows.
-#if ENABLE(OILPAN)
         m_frame->localDOMWindow()->registerProperty(this);
-#else
-        m_associatedDOMWindow = m_frame->localDOMWindow();
-        m_associatedDOMWindow->registerProperty(this);
-#endif
     }
 }
 
-#if !ENABLE(OILPAN)
-DOMWindowProperty::~DOMWindowProperty()
-{
-    if (m_associatedDOMWindow)
-        m_associatedDOMWindow->unregisterProperty(this);
-}
-#endif
-
 void DOMWindowProperty::willDestroyGlobalObjectInFrame()
 {
     // If the property is getting this callback it must have been
     // created with a LocalFrame and it should still have it.
     ASSERT(m_frame);
     m_frame = nullptr;
-
-#if !ENABLE(OILPAN)
-    // LocalDOMWindow will along with notifying DOMWindowProperty objects of
-    // impending destruction, unilaterally clear out its registered set.
-    // Consequently, no explicit unregisteration required by DOMWindowProperty;
-    // here or when destructed.
-    ASSERT(m_associatedDOMWindow);
-    m_associatedDOMWindow = nullptr;
-#endif
 }
 
 void DOMWindowProperty::willDetachGlobalObjectFromFrame()
@@ -82,10 +57,6 @@
     // If the property is getting this callback it must have been
     // created with a LocalFrame and it should still have it.
     ASSERT(m_frame);
-#if !ENABLE(OILPAN)
-    // Ditto for its associated LocalDOMWindow.
-    ASSERT(m_associatedDOMWindow);
-#endif
 }
 
 DEFINE_TRACE(DOMWindowProperty)
diff --git a/third_party/WebKit/Source/core/frame/DOMWindowProperty.h b/third_party/WebKit/Source/core/frame/DOMWindowProperty.h
index 8da6260..e7e71459 100644
--- a/third_party/WebKit/Source/core/frame/DOMWindowProperty.h
+++ b/third_party/WebKit/Source/core/frame/DOMWindowProperty.h
@@ -46,18 +46,7 @@
     DECLARE_VIRTUAL_TRACE();
 
 protected:
-    // TODO(Oilpan): when ~DOMWindowProperty is removed, check classes that derive
-    // from it. Several will then be able to derive from GarbageCollected<> instead.
-#if !ENABLE(OILPAN)
-    virtual ~DOMWindowProperty();
-#endif
-
     Member<LocalFrame> m_frame;
-
-#if !ENABLE(OILPAN)
-private:
-    LocalDOMWindow* m_associatedDOMWindow;
-#endif
 };
 
 } // namespace blink
diff --git a/third_party/WebKit/Source/core/frame/FrameView.cpp b/third_party/WebKit/Source/core/frame/FrameView.cpp
index 003da4f2..15a7771 100644
--- a/third_party/WebKit/Source/core/frame/FrameView.cpp
+++ b/third_party/WebKit/Source/core/frame/FrameView.cpp
@@ -184,11 +184,6 @@
 FrameView::~FrameView()
 {
     ASSERT(m_hasBeenDisposed);
-#if !ENABLE(OILPAN)
-    // Verify that the LocalFrame has a different FrameView or
-    // that it is being detached and destructed.
-    ASSERT(frame().view() != this || !layoutView());
-#endif
 }
 
 DEFINE_TRACE(FrameView)
@@ -935,13 +930,6 @@
 
     performPreLayoutTasks();
 
-#if !ENABLE(OILPAN)
-    // If there is only one ref to this view left, then its going to be destroyed as soon as we exit,
-    // so there's no point to continuing to layout
-    if (protector->hasOneRef())
-        return;
-#endif
-
     Document* document = m_frame->document();
 
     // If the layout view was marked as needing layout after we added items in the subtree roots we need
diff --git a/third_party/WebKit/Source/core/frame/LocalDOMWindow.cpp b/third_party/WebKit/Source/core/frame/LocalDOMWindow.cpp
index a943a82..3359b22 100644
--- a/third_party/WebKit/Source/core/frame/LocalDOMWindow.cpp
+++ b/third_party/WebKit/Source/core/frame/LocalDOMWindow.cpp
@@ -91,12 +91,6 @@
     return new WindowFrameObserver(window, frame);
 }
 
-#if !ENABLE(OILPAN)
-LocalDOMWindow::WindowFrameObserver::~WindowFrameObserver()
-{
-}
-#endif
-
 DEFINE_TRACE(LocalDOMWindow::WindowFrameObserver)
 {
     visitor->trace(m_window);
@@ -297,9 +291,7 @@
     , m_hasBeenReset(false)
 #endif
 {
-#if ENABLE(OILPAN)
     ThreadState::current()->registerPreFinalizer(this);
-#endif
 }
 
 void LocalDOMWindow::clearDocument()
@@ -451,14 +443,8 @@
 
 LocalDOMWindow::~LocalDOMWindow()
 {
-#if ENABLE(OILPAN)
     // Cleared when detaching document.
     ASSERT(!m_eventQueue);
-#else
-    ASSERT(m_hasBeenReset);
-    ASSERT(m_document->isStopped());
-    clearDocument();
-#endif
 }
 
 void LocalDOMWindow::dispose()
@@ -470,9 +456,6 @@
     // Arrange for that removal to happen using a prefinalizer action. Making LocalDOMWindow
     // eager finalizable is problematic as other eagerly finalized objects may well
     // want to access their associated LocalDOMWindow from their destructors.
-    //
-    // (Non-Oilpan, LocalDOMWindow::reset() will always be invoked, the last opportunity
-    // being via ~LocalFrame's setDOMWindow() call. Asserted for in the destructor.)
     if (!frame())
         return;
 
diff --git a/third_party/WebKit/Source/core/frame/LocalFrame.cpp b/third_party/WebKit/Source/core/frame/LocalFrame.cpp
index 68a108f1..25784320 100644
--- a/third_party/WebKit/Source/core/frame/LocalFrame.cpp
+++ b/third_party/WebKit/Source/core/frame/LocalFrame.cpp
@@ -236,11 +236,6 @@
     // Verify that the FrameView has been cleared as part of detaching
     // the frame owner.
     ASSERT(!m_view);
-#if !ENABLE(OILPAN)
-    // Oilpan: see setDOMWindow() comment why it is acceptable not to
-    // explicitly call setDOMWindow() here.
-    setDOMWindow(nullptr);
-#endif
 }
 
 DEFINE_TRACE(LocalFrame)
diff --git a/third_party/WebKit/Source/core/frame/Navigator.cpp b/third_party/WebKit/Source/core/frame/Navigator.cpp
index 9db07da5..c2461fb 100644
--- a/third_party/WebKit/Source/core/frame/Navigator.cpp
+++ b/third_party/WebKit/Source/core/frame/Navigator.cpp
@@ -40,10 +40,6 @@
 {
 }
 
-Navigator::~Navigator()
-{
-}
-
 String Navigator::productSub() const
 {
     return "20030107";
diff --git a/third_party/WebKit/Source/core/frame/Navigator.h b/third_party/WebKit/Source/core/frame/Navigator.h
index 395b935..b88c9cf4 100644
--- a/third_party/WebKit/Source/core/frame/Navigator.h
+++ b/third_party/WebKit/Source/core/frame/Navigator.h
@@ -37,7 +37,7 @@
 typedef int ExceptionCode;
 
 class Navigator final
-    : public GarbageCollectedFinalized<Navigator>
+    : public GarbageCollected<Navigator>
     , public NavigatorCPU
     , public NavigatorID
     , public NavigatorLanguage
@@ -53,8 +53,6 @@
         return new Navigator(frame);
     }
 
-    virtual ~Navigator();
-
     bool cookieEnabled() const;
 
     String productSub() const;
diff --git a/third_party/WebKit/Source/core/frame/Screen.h b/third_party/WebKit/Source/core/frame/Screen.h
index 4a4dc6b2..37917ba 100644
--- a/third_party/WebKit/Source/core/frame/Screen.h
+++ b/third_party/WebKit/Source/core/frame/Screen.h
@@ -39,7 +39,7 @@
 
 class LocalFrame;
 
-class Screen final : public GarbageCollectedFinalized<Screen>, public ScriptWrappable, public DOMWindowProperty, public Supplementable<Screen> {
+class Screen final : public GarbageCollected<Screen>, public ScriptWrappable, public DOMWindowProperty, public Supplementable<Screen> {
     DEFINE_WRAPPERTYPEINFO();
     USING_GARBAGE_COLLECTED_MIXIN(Screen);
 public:
diff --git a/third_party/WebKit/Source/core/frame/Settings.in b/third_party/WebKit/Source/core/frame/Settings.in
index 7e027832..69f1dbd 100644
--- a/third_party/WebKit/Source/core/frame/Settings.in
+++ b/third_party/WebKit/Source/core/frame/Settings.in
@@ -363,8 +363,6 @@
 
 lowPriorityIframes initial=false
 
-reportWheelOverscroll initial=false
-
 mainResourceOnlyProgress initial=false
 
 # Do we want to try to save screen real estate in the media player by hiding
diff --git a/third_party/WebKit/Source/core/frame/UseCounter.cpp b/third_party/WebKit/Source/core/frame/UseCounter.cpp
index 7ab2b2d..795dfc8 100644
--- a/third_party/WebKit/Source/core/frame/UseCounter.cpp
+++ b/third_party/WebKit/Source/core/frame/UseCounter.cpp
@@ -696,10 +696,10 @@
     if (!host)
         return false;
 
-    CSSPropertyID propertyID = cssPropertyID(string);
-    if (propertyID == CSSPropertyInvalid)
+    CSSPropertyID unresolvedProperty = unresolvedCSSPropertyID(string);
+    if (unresolvedProperty == CSSPropertyInvalid)
         return false;
-    return host->useCounter().isCounted(propertyID);
+    return host->useCounter().isCounted(unresolvedProperty);
 }
 
 void UseCounter::count(const ExecutionContext* context, Feature feature)
diff --git a/third_party/WebKit/Source/core/frame/UseCounter.h b/third_party/WebKit/Source/core/frame/UseCounter.h
index fd930d72..ba5f141 100644
--- a/third_party/WebKit/Source/core/frame/UseCounter.h
+++ b/third_party/WebKit/Source/core/frame/UseCounter.h
@@ -1133,7 +1133,7 @@
     // Return whether the CSSPropertyID was previously counted for this document.
     // NOTE: only for use in testing.
     static bool isCounted(Document&, const String&);
-    bool isCounted(CSSPropertyID);
+    bool isCounted(CSSPropertyID unresolvedProperty);
 
     void didCommitLoad();
 
diff --git a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp
index fe38f1d..43257c2 100644
--- a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp
+++ b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp
@@ -1060,31 +1060,6 @@
     return false;
 }
 
-bool ContentSecurityPolicy::isScriptResource(const ResourceRequest& resourceRequest)
-{
-    return WebURLRequest::RequestContextScript == resourceRequest.requestContext() || WebURLRequest::RequestContextImport == resourceRequest.requestContext() || WebURLRequest::RequestContextXSLT == resourceRequest.requestContext() || WebURLRequest::RequestContextPrefetch == resourceRequest.requestContext();
-}
-
-bool ContentSecurityPolicy::isStyleResource(const ResourceRequest& resourceRequest)
-{
-    return WebURLRequest::RequestContextStyle == resourceRequest.requestContext() || WebURLRequest::RequestContextPrefetch == resourceRequest.requestContext();
-}
-
-bool ContentSecurityPolicy::isImageResource(const ResourceRequest& resourceRequest)
-{
-    return WebURLRequest::RequestContextImage == resourceRequest.requestContext() || WebURLRequest::RequestContextFavicon == resourceRequest.requestContext() || WebURLRequest::RequestContextImageSet == resourceRequest.requestContext() || WebURLRequest::RequestContextPrefetch == resourceRequest.requestContext();
-}
-
-bool ContentSecurityPolicy::isFontResource(const ResourceRequest& resourceRequest)
-{
-    return WebURLRequest::RequestContextFont == resourceRequest.requestContext() || WebURLRequest::RequestContextPrefetch == resourceRequest.requestContext();
-}
-
-bool ContentSecurityPolicy::isMediaResource(const ResourceRequest& resourceRequest)
-{
-    return WebURLRequest::RequestContextAudio == resourceRequest.requestContext() || WebURLRequest::RequestContextVideo == resourceRequest.requestContext() || WebURLRequest::RequestContextTrack == resourceRequest.requestContext() || WebURLRequest::RequestContextPrefetch == resourceRequest.requestContext();
-}
-
 bool ContentSecurityPolicy::shouldSendViolationReport(const String& report) const
 {
     // Collisions have no security impact, so we can save space by storing only the string's hash rather than the whole report.
diff --git a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.h b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.h
index 6a5c141..84224b2 100644
--- a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.h
+++ b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.h
@@ -261,15 +261,6 @@
 
     static bool isDirectiveName(const String&);
 
-    // These functions are used to debug using ResourceContext to apply
-    // CSP directives instead of Resource::Type, by checking that the
-    // ResourceContext is as expected. See crbug.com/474412
-    static bool isScriptResource(const ResourceRequest&);
-    static bool isStyleResource(const ResourceRequest&);
-    static bool isImageResource(const ResourceRequest&);
-    static bool isFontResource(const ResourceRequest&);
-    static bool isMediaResource(const ResourceRequest&);
-
     Document* document() const;
 
 private:
diff --git a/third_party/WebKit/Source/core/html/FormAssociatedElement.cpp b/third_party/WebKit/Source/core/html/FormAssociatedElement.cpp
index d012dc1..04dd2452 100644
--- a/third_party/WebKit/Source/core/html/FormAssociatedElement.cpp
+++ b/third_party/WebKit/Source/core/html/FormAssociatedElement.cpp
@@ -86,7 +86,7 @@
     if (!m_formWasSetByParser || !m_form || NodeTraversal::highestAncestorOrSelf(*insertionPoint) != NodeTraversal::highestAncestorOrSelf(*m_form.get()))
         resetFormOwner();
 
-    if (!insertionPoint->inDocument())
+    if (!insertionPoint->inShadowIncludingDocument())
         return;
 
     HTMLElement* element = toHTMLElement(this);
@@ -97,7 +97,7 @@
 void FormAssociatedElement::removedFrom(ContainerNode* insertionPoint)
 {
     HTMLElement* element = toHTMLElement(this);
-    if (insertionPoint->inDocument() && element->fastHasAttribute(formAttr)) {
+    if (insertionPoint->inShadowIncludingDocument() && element->fastHasAttribute(formAttr)) {
         setFormAttributeTargetObserver(nullptr);
         resetFormOwner();
         return;
@@ -113,7 +113,7 @@
     const AtomicString& formId(element->fastGetAttribute(formAttr));
     // 3. If the element is reassociateable, has a form content attribute, and
     // is itself in a Document, then run these substeps:
-    if (!formId.isNull() && element->inDocument()) {
+    if (!formId.isNull() && element->inShadowIncludingDocument()) {
         // 3.1. If the first element in the Document to have an ID that is
         // case-sensitively equal to the element's form content attribute's
         // value is a form element, then associate the form-associated element
@@ -138,7 +138,7 @@
 
 void FormAssociatedElement::associateByParser(HTMLFormElement* form)
 {
-    if (form && form->inDocument()) {
+    if (form && form->inShadowIncludingDocument()) {
         m_formWasSetByParser = true;
         setForm(form);
         form->didAssociateByParser();
@@ -171,7 +171,7 @@
 
 void FormAssociatedElement::didChangeForm()
 {
-    if (!m_formWasSetByParser && m_form && m_form->inDocument()) {
+    if (!m_formWasSetByParser && m_form && m_form->inShadowIncludingDocument()) {
         HTMLElement* element = toHTMLElement(this);
         element->document().didAssociateFormControl(element);
     }
@@ -289,7 +289,7 @@
 {
     HTMLElement* element = toHTMLElement(this);
     const AtomicString& formId(element->fastGetAttribute(formAttr));
-    if (!formId.isNull() && element->inDocument())
+    if (!formId.isNull() && element->inShadowIncludingDocument())
         setFormAttributeTargetObserver(FormAttributeTargetObserver::create(formId, this));
     else
         setFormAttributeTargetObserver(nullptr);
diff --git a/third_party/WebKit/Source/core/html/HTMLBaseElement.cpp b/third_party/WebKit/Source/core/html/HTMLBaseElement.cpp
index ddf07c7..3b94b3b 100644
--- a/third_party/WebKit/Source/core/html/HTMLBaseElement.cpp
+++ b/third_party/WebKit/Source/core/html/HTMLBaseElement.cpp
@@ -50,7 +50,7 @@
 Node::InsertionNotificationRequest HTMLBaseElement::insertedInto(ContainerNode* insertionPoint)
 {
     HTMLElement::insertedInto(insertionPoint);
-    if (insertionPoint->inDocument())
+    if (insertionPoint->inShadowIncludingDocument())
         document().processBaseElement();
     return InsertionDone;
 }
@@ -58,7 +58,7 @@
 void HTMLBaseElement::removedFrom(ContainerNode* insertionPoint)
 {
     HTMLElement::removedFrom(insertionPoint);
-    if (insertionPoint->inDocument())
+    if (insertionPoint->inShadowIncludingDocument())
         document().processBaseElement();
 }
 
diff --git a/third_party/WebKit/Source/core/html/HTMLButtonElement.cpp b/third_party/WebKit/Source/core/html/HTMLButtonElement.cpp
index c73efb4..ef85e227 100644
--- a/third_party/WebKit/Source/core/html/HTMLButtonElement.cpp
+++ b/third_party/WebKit/Source/core/html/HTMLButtonElement.cpp
@@ -101,7 +101,7 @@
         else
             m_type = SUBMIT;
         setNeedsWillValidateCheck();
-        if (formOwner() && inDocument())
+        if (formOwner() && inShadowIncludingDocument())
             formOwner()->invalidateDefaultButtonStyle();
     } else {
         if (name == formactionAttr)
diff --git a/third_party/WebKit/Source/core/html/HTMLDialogElement.cpp b/third_party/WebKit/Source/core/html/HTMLDialogElement.cpp
index 953a6ce..018752047 100644
--- a/third_party/WebKit/Source/core/html/HTMLDialogElement.cpp
+++ b/third_party/WebKit/Source/core/html/HTMLDialogElement.cpp
@@ -153,7 +153,7 @@
         exceptionState.throwDOMException(InvalidStateError, "The element already has an 'open' attribute, and therefore cannot be opened modally.");
         return;
     }
-    if (!inDocument()) {
+    if (!inShadowIncludingDocument()) {
         exceptionState.throwDOMException(InvalidStateError, "The element is not in a Document.");
         return;
     }
diff --git a/third_party/WebKit/Source/core/html/HTMLFormControlElement.cpp b/third_party/WebKit/Source/core/html/HTMLFormControlElement.cpp
index 5c439f7..11a4530b 100644
--- a/third_party/WebKit/Source/core/html/HTMLFormControlElement.cpp
+++ b/third_party/WebKit/Source/core/html/HTMLFormControlElement.cpp
@@ -278,7 +278,7 @@
     fieldSetAncestorsSetNeedsValidityCheck(insertionPoint);
 
     // Trigger for elements outside of forms.
-    if (!formOwner() && insertionPoint->inDocument())
+    if (!formOwner() && insertionPoint->inShadowIncludingDocument())
         document().didAssociateFormControl(this);
 
     return InsertionDone;
@@ -309,7 +309,7 @@
 {
     FormAssociatedElement::didChangeForm();
     formOwnerSetNeedsValidityCheck();
-    if (formOwner() && inDocument() && canBeSuccessfulSubmitButton())
+    if (formOwner() && inShadowIncludingDocument() && canBeSuccessfulSubmitButton())
         formOwner()->invalidateDefaultButtonStyle();
 }
 
@@ -544,7 +544,7 @@
     RawPtr<HTMLFormControlElement> protector(this);
     RawPtr<Document> originalDocument(document());
     DispatchEventResult dispatchResult = dispatchEvent(Event::createCancelable(EventTypeNames::invalid));
-    if (dispatchResult == DispatchEventResult::NotCanceled && unhandledInvalidControls && inDocument() && originalDocument == document())
+    if (dispatchResult == DispatchEventResult::NotCanceled && unhandledInvalidControls && inShadowIncludingDocument() && originalDocument == document())
         unhandledInvalidControls->append(this);
     return false;
 }
diff --git a/third_party/WebKit/Source/core/html/HTMLFormControlElementWithState.cpp b/third_party/WebKit/Source/core/html/HTMLFormControlElementWithState.cpp
index 8e953ad..f0c6079 100644
--- a/third_party/WebKit/Source/core/html/HTMLFormControlElementWithState.cpp
+++ b/third_party/WebKit/Source/core/html/HTMLFormControlElementWithState.cpp
@@ -44,14 +44,14 @@
 
 Node::InsertionNotificationRequest HTMLFormControlElementWithState::insertedInto(ContainerNode* insertionPoint)
 {
-    if (insertionPoint->inDocument() && !containingShadowRoot())
+    if (insertionPoint->inShadowIncludingDocument() && !containingShadowRoot())
         document().formController().registerStatefulFormControl(*this);
     return HTMLFormControlElement::insertedInto(insertionPoint);
 }
 
 void HTMLFormControlElementWithState::removedFrom(ContainerNode* insertionPoint)
 {
-    if (insertionPoint->inDocument() && !containingShadowRoot() && !insertionPoint->containingShadowRoot())
+    if (insertionPoint->inShadowIncludingDocument() && !containingShadowRoot() && !insertionPoint->containingShadowRoot())
         document().formController().unregisterStatefulFormControl(*this);
     HTMLFormControlElement::removedFrom(insertionPoint);
 }
@@ -75,7 +75,7 @@
 bool HTMLFormControlElementWithState::shouldSaveAndRestoreFormControlState() const
 {
     // We don't save/restore control state in a form with autocomplete=off.
-    return inDocument() && shouldAutocomplete();
+    return inShadowIncludingDocument() && shouldAutocomplete();
 }
 
 FormControlState HTMLFormControlElementWithState::saveFormControlState() const
diff --git a/third_party/WebKit/Source/core/html/HTMLFormElement.cpp b/third_party/WebKit/Source/core/html/HTMLFormElement.cpp
index fc459a3..6140e825 100644
--- a/third_party/WebKit/Source/core/html/HTMLFormElement.cpp
+++ b/third_party/WebKit/Source/core/html/HTMLFormElement.cpp
@@ -149,7 +149,7 @@
 {
     HTMLElement::insertedInto(insertionPoint);
     logAddElementIfIsolatedWorldAndInDocument("form", methodAttr, actionAttr);
-    if (insertionPoint->inDocument())
+    if (insertionPoint->inShadowIncludingDocument())
         this->document().didAssociateFormControl(this);
     return InsertionDone;
 }
@@ -605,7 +605,7 @@
     Node* scope = mutableThis;
     if (m_hasElementsAssociatedByParser)
         scope = &NodeTraversal::highestAncestorOrSelf(*mutableThis);
-    if (inDocument() && m_hasElementsAssociatedByFormAttribute)
+    if (inShadowIncludingDocument() && m_hasElementsAssociatedByFormAttribute)
         scope = &treeScope().rootNode();
     ASSERT(scope);
     collectAssociatedElements(*scope, mutableThis->m_associatedElements);
diff --git a/third_party/WebKit/Source/core/html/HTMLFrameElementBase.cpp b/third_party/WebKit/Source/core/html/HTMLFrameElementBase.cpp
index 4af1d5c..8dd78578 100644
--- a/third_party/WebKit/Source/core/html/HTMLFrameElementBase.cpp
+++ b/third_party/WebKit/Source/core/html/HTMLFrameElementBase.cpp
@@ -188,7 +188,7 @@
 {
     m_URL = AtomicString(str);
 
-    if (inDocument())
+    if (inShadowIncludingDocument())
         openURL(false);
 }
 
diff --git a/third_party/WebKit/Source/core/html/HTMLFrameOwnerElement.cpp b/third_party/WebKit/Source/core/html/HTMLFrameOwnerElement.cpp
index 95fdf87..b988806 100644
--- a/third_party/WebKit/Source/core/html/HTMLFrameOwnerElement.cpp
+++ b/third_party/WebKit/Source/core/html/HTMLFrameOwnerElement.cpp
@@ -153,7 +153,7 @@
     // Make sure we will not end up with two frames referencing the same owner element.
     ASSERT(!m_contentFrame || m_contentFrame->owner() != this);
     // Disconnected frames should not be allowed to load.
-    ASSERT(inDocument());
+    ASSERT(inShadowIncludingDocument());
     m_contentFrame = &frame;
 
     for (ContainerNode* node = this; node; node = node->parentOrShadowHostNode())
diff --git a/third_party/WebKit/Source/core/html/HTMLFrameSetElement.cpp b/third_party/WebKit/Source/core/html/HTMLFrameSetElement.cpp
index b594c0f..9d3ace97 100644
--- a/third_party/WebKit/Source/core/html/HTMLFrameSetElement.cpp
+++ b/third_party/WebKit/Source/core/html/HTMLFrameSetElement.cpp
@@ -196,7 +196,7 @@
 
 Node::InsertionNotificationRequest HTMLFrameSetElement::insertedInto(ContainerNode* insertionPoint)
 {
-    if (insertionPoint->inDocument() && document().frame()) {
+    if (insertionPoint->inShadowIncludingDocument() && document().frame()) {
         // A document using <frameset> likely won't literally have a body, but as far as the client is concerned, the frameset is effectively the body.
         document().frame()->loader().client()->dispatchWillInsertBody();
     }
diff --git a/third_party/WebKit/Source/core/html/HTMLIFrameElement.cpp b/third_party/WebKit/Source/core/html/HTMLIFrameElement.cpp
index 6c63c8b..31bde6d 100644
--- a/third_party/WebKit/Source/core/html/HTMLIFrameElement.cpp
+++ b/third_party/WebKit/Source/core/html/HTMLIFrameElement.cpp
@@ -94,7 +94,7 @@
 void HTMLIFrameElement::parseAttribute(const QualifiedName& name, const AtomicString& oldValue, const AtomicString& value)
 {
     if (name == nameAttr) {
-        if (inDocument() && document().isHTMLDocument() && !isInShadowTree()) {
+        if (inShadowIncludingDocument() && document().isHTMLDocument() && !isInShadowTree()) {
             HTMLDocument& document = toHTMLDocument(this->document());
             document.removeExtraNamedItem(m_name);
             document.addExtraNamedItem(value);
@@ -127,7 +127,7 @@
 Node::InsertionNotificationRequest HTMLIFrameElement::insertedInto(ContainerNode* insertionPoint)
 {
     InsertionNotificationRequest result = HTMLFrameElementBase::insertedInto(insertionPoint);
-    if (insertionPoint->inDocument() && document().isHTMLDocument() && !insertionPoint->isInShadowTree())
+    if (insertionPoint->inShadowIncludingDocument() && document().isHTMLDocument() && !insertionPoint->isInShadowTree())
         toHTMLDocument(document()).addExtraNamedItem(m_name);
     logAddElementIfIsolatedWorldAndInDocument("iframe", srcAttr);
     return result;
@@ -136,7 +136,7 @@
 void HTMLIFrameElement::removedFrom(ContainerNode* insertionPoint)
 {
     HTMLFrameElementBase::removedFrom(insertionPoint);
-    if (insertionPoint->inDocument() && document().isHTMLDocument() && !insertionPoint->isInShadowTree())
+    if (insertionPoint->inShadowIncludingDocument() && document().isHTMLDocument() && !insertionPoint->isInShadowTree())
         toHTMLDocument(document()).removeExtraNamedItem(m_name);
 }
 
diff --git a/third_party/WebKit/Source/core/html/HTMLImageElement.cpp b/third_party/WebKit/Source/core/html/HTMLImageElement.cpp
index 084a218..2516ceb 100644
--- a/third_party/WebKit/Source/core/html/HTMLImageElement.cpp
+++ b/third_party/WebKit/Source/core/html/HTMLImageElement.cpp
@@ -98,7 +98,7 @@
     , m_referrerPolicy(ReferrerPolicyDefault)
 {
     setHasCustomStyleCallbacks();
-    if (form && form->inDocument()) {
+    if (form && form->inShadowIncludingDocument()) {
 #if ENABLE(OILPAN)
         m_form = form;
 #else
@@ -411,7 +411,7 @@
 
     // If we have been inserted from a layoutObject-less document,
     // our loader may have not fetched the image, so do it now.
-    if ((insertionPoint->inDocument() && !imageLoader().image()) || imageWasModified)
+    if ((insertionPoint->inShadowIncludingDocument() && !imageLoader().image()) || imageWasModified)
         imageLoader().updateFromElement(ImageLoader::UpdateNormal, m_referrerPolicy);
 
     return HTMLElement::insertedInto(insertionPoint);
diff --git a/third_party/WebKit/Source/core/html/HTMLInputElement.cpp b/third_party/WebKit/Source/core/html/HTMLInputElement.cpp
index 01285de..f756cd4 100644
--- a/third_party/WebKit/Source/core/html/HTMLInputElement.cpp
+++ b/third_party/WebKit/Source/core/html/HTMLInputElement.cpp
@@ -534,7 +534,7 @@
     addToRadioButtonGroup();
 
     setNeedsValidityCheck();
-    if ((couldBeSuccessfulSubmitButton || canBeSuccessfulSubmitButton()) && formOwner() && inDocument())
+    if ((couldBeSuccessfulSubmitButton || canBeSuccessfulSubmitButton()) && formOwner() && inShadowIncludingDocument())
         formOwner()->invalidateDefaultButtonStyle();
     notifyFormStateChanged();
 }
@@ -910,7 +910,7 @@
 
 void HTMLInputElement::dispatchChangeEventIfNeeded()
 {
-    if (inDocument() && m_inputType->shouldSendChangeEventAfterCheckedChanged())
+    if (inShadowIncludingDocument() && m_inputType->shouldSendChangeEventAfterCheckedChanged())
         dispatchChangeEvent();
 }
 
@@ -949,7 +949,7 @@
     // unchecked to match other browsers. DOM is not a useful standard for this
     // because it says only to fire change events at "lose focus" time, which is
     // definitely wrong in practice for these types of elements.
-    if (eventBehavior != DispatchNoEvent && inDocument() && m_inputType->shouldSendChangeEventAfterCheckedChanged()) {
+    if (eventBehavior != DispatchNoEvent && inShadowIncludingDocument() && m_inputType->shouldSendChangeEventAfterCheckedChanged()) {
         setTextAsOfLastFormControlChangeEvent(String());
         if (eventBehavior == DispatchInputAndChangeEvent)
             dispatchFormControlInputEvent();
@@ -1526,7 +1526,7 @@
 Node::InsertionNotificationRequest HTMLInputElement::insertedInto(ContainerNode* insertionPoint)
 {
     HTMLTextFormControlElement::insertedInto(insertionPoint);
-    if (insertionPoint->inDocument() && !form())
+    if (insertionPoint->inShadowIncludingDocument() && !form())
         addToRadioButtonGroup();
     resetListAttributeTargetObserver();
     logAddElementIfIsolatedWorldAndInDocument("input", typeAttr, formactionAttr);
@@ -1536,10 +1536,10 @@
 void HTMLInputElement::removedFrom(ContainerNode* insertionPoint)
 {
     m_inputTypeView->closePopupView();
-    if (insertionPoint->inDocument() && !form())
+    if (insertionPoint->inShadowIncludingDocument() && !form())
         removeFromRadioButtonGroup();
     HTMLTextFormControlElement::removedFrom(insertionPoint);
-    ASSERT(!inDocument());
+    ASSERT(!inShadowIncludingDocument());
     resetListAttributeTargetObserver();
 }
 
@@ -1632,7 +1632,7 @@
 
 void HTMLInputElement::resetListAttributeTargetObserver()
 {
-    if (inDocument())
+    if (inShadowIncludingDocument())
         setListAttributeTargetObserver(ListAttributeTargetObserver::create(fastGetAttribute(listAttr), this));
     else
         setListAttributeTargetObserver(nullptr);
@@ -1764,7 +1764,7 @@
         return nullptr;
     if (HTMLFormElement* formElement = form())
         return &formElement->radioButtonGroupScope();
-    if (inDocument())
+    if (inShadowIncludingDocument())
         return &treeScope().radioButtonGroupScope();
     return nullptr;
 }
diff --git a/third_party/WebKit/Source/core/html/HTMLLabelElement.cpp b/third_party/WebKit/Source/core/html/HTMLLabelElement.cpp
index 6d182e7..8fb5e90f 100644
--- a/third_party/WebKit/Source/core/html/HTMLLabelElement.cpp
+++ b/third_party/WebKit/Source/core/html/HTMLLabelElement.cpp
@@ -136,7 +136,7 @@
 
 bool HTMLLabelElement::isInInteractiveContent(Node* node) const
 {
-    if (!containsIncludingShadowDOM(node))
+    if (!isShadowIncludingInclusiveAncestorOf(node))
         return false;
     while (node && this != node) {
         if (node->isHTMLElement() && toHTMLElement(node)->isInteractiveContent())
@@ -153,7 +153,7 @@
 
         // If we can't find a control or if the control received the click
         // event, then there's no need for us to do anything.
-        if (!element || (evt->target() && element->containsIncludingShadowDOM(evt->target()->toNode())))
+        if (!element || (evt->target() && element->isShadowIncludingInclusiveAncestorOf(evt->target()->toNode())))
             return;
 
         if (evt->target() && isInInteractiveContent(evt->target()->toNode()))
@@ -245,7 +245,7 @@
 
 void HTMLLabelElement::updateLabel(TreeScope& scope, const AtomicString& oldForAttributeValue, const AtomicString& newForAttributeValue)
 {
-    if (!inDocument())
+    if (!inShadowIncludingDocument())
         return;
 
     if (oldForAttributeValue == newForAttributeValue)
@@ -268,7 +268,7 @@
     }
 
     // Trigger for elements outside of forms.
-    if (!formOwner() && insertionPoint->inDocument())
+    if (!formOwner() && insertionPoint->inShadowIncludingDocument())
         document().didAssociateFormControl(this);
 
     return result;
diff --git a/third_party/WebKit/Source/core/html/HTMLLinkElement.cpp b/third_party/WebKit/Source/core/html/HTMLLinkElement.cpp
index 3bae4fa3..c1e51f1 100644
--- a/third_party/WebKit/Source/core/html/HTMLLinkElement.cpp
+++ b/third_party/WebKit/Source/core/html/HTMLLinkElement.cpp
@@ -166,7 +166,7 @@
     m_sizes->setObserver(nullptr);
     m_relList->setObserver(nullptr);
     m_link.clear();
-    if (inDocument())
+    if (inShadowIncludingDocument())
         document().styleEngine().removeStyleSheetCandidateNode(this);
     linkLoadEventSender().cancelEvent(this);
 #endif
@@ -212,7 +212,7 @@
 
 bool HTMLLinkElement::shouldLoadLink()
 {
-    return inDocument();
+    return inShadowIncludingDocument();
 }
 
 bool HTMLLinkElement::loadLink(const String& type, const String& as, const String& media, const KURL& url)
@@ -222,7 +222,7 @@
 
 LinkResource* HTMLLinkElement::linkResourceToProcess()
 {
-    bool visible = inDocument() && !m_isInShadowTree;
+    bool visible = inShadowIncludingDocument() && !m_isInShadowTree;
     if (!visible) {
         ASSERT(!linkStyle() || !linkStyle()->hasSheet());
         return nullptr;
@@ -280,7 +280,7 @@
 {
     HTMLElement::insertedInto(insertionPoint);
     logAddElementIfIsolatedWorldAndInDocument("link", relAttr, hrefAttr);
-    if (!insertionPoint->inDocument())
+    if (!insertionPoint->inShadowIncludingDocument())
         return InsertionDone;
 
     m_isInShadowTree = isInShadowTree();
@@ -303,7 +303,7 @@
 void HTMLLinkElement::removedFrom(ContainerNode* insertionPoint)
 {
     HTMLElement::removedFrom(insertionPoint);
-    if (!insertionPoint->inDocument())
+    if (!insertionPoint->inShadowIncludingDocument())
         return;
 
     m_linkLoader->released();
@@ -514,7 +514,7 @@
 
 void LinkStyle::setCSSStyleSheet(const String& href, const KURL& baseURL, const String& charset, const CSSStyleSheetResource* cachedStyleSheet)
 {
-    if (!m_owner->inDocument()) {
+    if (!m_owner->inShadowIncludingDocument()) {
         ASSERT(!m_sheet);
         return;
     }
diff --git a/third_party/WebKit/Source/core/html/HTMLMapElement.cpp b/third_party/WebKit/Source/core/html/HTMLMapElement.cpp
index e462d77fe..3a5c8f9b 100644
--- a/third_party/WebKit/Source/core/html/HTMLMapElement.cpp
+++ b/third_party/WebKit/Source/core/html/HTMLMapElement.cpp
@@ -89,13 +89,13 @@
             if (document().isHTMLDocument())
                 return;
         }
-        if (inDocument())
+        if (inShadowIncludingDocument())
             treeScope().removeImageMap(this);
         String mapName = value;
         if (mapName[0] == '#')
             mapName = mapName.substring(1);
         m_name = AtomicString(document().isHTMLDocument() ? mapName.lower() : mapName);
-        if (inDocument())
+        if (inShadowIncludingDocument())
             treeScope().addImageMap(this);
 
         return;
@@ -111,14 +111,14 @@
 
 Node::InsertionNotificationRequest HTMLMapElement::insertedInto(ContainerNode* insertionPoint)
 {
-    if (insertionPoint->inDocument())
+    if (insertionPoint->inShadowIncludingDocument())
         treeScope().addImageMap(this);
     return HTMLElement::insertedInto(insertionPoint);
 }
 
 void HTMLMapElement::removedFrom(ContainerNode* insertionPoint)
 {
-    if (insertionPoint->inDocument())
+    if (insertionPoint->inShadowIncludingDocument())
         treeScope().removeImageMap(this);
     HTMLElement::removedFrom(insertionPoint);
 }
diff --git a/third_party/WebKit/Source/core/html/HTMLMarqueeElement.cpp b/third_party/WebKit/Source/core/html/HTMLMarqueeElement.cpp
index ac089c6..e384700 100644
--- a/third_party/WebKit/Source/core/html/HTMLMarqueeElement.cpp
+++ b/third_party/WebKit/Source/core/html/HTMLMarqueeElement.cpp
@@ -56,7 +56,7 @@
 Node::InsertionNotificationRequest HTMLMarqueeElement::insertedInto(ContainerNode* insertionPoint)
 {
     HTMLElement::insertedInto(insertionPoint);
-    if (inDocument()) {
+    if (inShadowIncludingDocument()) {
         V8HTMLMarqueeElement::PrivateScript::attachedCallbackMethod(document().frame(), this);
     }
     return InsertionDone;
@@ -65,7 +65,7 @@
 void HTMLMarqueeElement::removedFrom(ContainerNode* insertionPoint)
 {
     HTMLElement::removedFrom(insertionPoint);
-    if (insertionPoint->inDocument()) {
+    if (insertionPoint->inShadowIncludingDocument()) {
         V8HTMLMarqueeElement::PrivateScript::detachedCallbackMethod(insertionPoint->document().frame(), this);
     }
 }
diff --git a/third_party/WebKit/Source/core/html/HTMLMediaElement.cpp b/third_party/WebKit/Source/core/html/HTMLMediaElement.cpp
index 06d4a93..b63151e 100644
--- a/third_party/WebKit/Source/core/html/HTMLMediaElement.cpp
+++ b/third_party/WebKit/Source/core/html/HTMLMediaElement.cpp
@@ -629,7 +629,7 @@
     WTF_LOG(Media, "HTMLMediaElement::insertedInto(%p, %p)", this, insertionPoint);
 
     HTMLElement::insertedInto(insertionPoint);
-    if (insertionPoint->inDocument()) {
+    if (insertionPoint->inShadowIncludingDocument()) {
         UseCounter::count(document(), UseCounter::HTMLMediaElementInDocument);
         if (!getAttribute(srcAttr).isEmpty() && m_networkState == NETWORK_EMPTY) {
             m_ignorePreloadNone = false;
@@ -3474,13 +3474,13 @@
 
     assertShadowRootChildren(shadowRoot);
 
-    if (!shouldShowControls() || !inDocument())
+    if (!shouldShowControls() || !inShadowIncludingDocument())
         mediaControls->hide();
 }
 
 void HTMLMediaElement::configureMediaControls()
 {
-    if (!inDocument()) {
+    if (!inShadowIncludingDocument()) {
         if (mediaControls())
             mediaControls()->hide();
         return;
diff --git a/third_party/WebKit/Source/core/html/HTMLMetaElement-in.cpp b/third_party/WebKit/Source/core/html/HTMLMetaElement-in.cpp
index 41335e85..d31bbb83 100644
--- a/third_party/WebKit/Source/core/html/HTMLMetaElement-in.cpp
+++ b/third_party/WebKit/Source/core/html/HTMLMetaElement-in.cpp
@@ -455,7 +455,7 @@
 
 static bool inDocumentHead(HTMLMetaElement* element)
 {
-    if (!element->inDocument())
+    if (!element->inShadowIncludingDocument())
         return false;
 
     return Traversal<HTMLHeadElement>::firstAncestor(*element);
@@ -463,7 +463,7 @@
 
 void HTMLMetaElement::process()
 {
-    if (!inDocument())
+    if (!inShadowIncludingDocument())
         return;
 
     // All below situations require a content attribute (which can be the empty string).
diff --git a/third_party/WebKit/Source/core/html/HTMLObjectElement.cpp b/third_party/WebKit/Source/core/html/HTMLObjectElement.cpp
index e57dd59..572d450 100644
--- a/third_party/WebKit/Source/core/html/HTMLObjectElement.cpp
+++ b/third_party/WebKit/Source/core/html/HTMLObjectElement.cpp
@@ -319,7 +319,7 @@
 
 void HTMLObjectElement::childrenChanged(const ChildrenChange& change)
 {
-    if (inDocument() && !useFallbackContent()) {
+    if (inShadowIncludingDocument() && !useFallbackContent()) {
         setNeedsWidgetUpdate(true);
         lazyReattachIfNeeded();
     }
@@ -364,7 +364,7 @@
     if (useFallbackContent())
         return;
 
-    if (!inDocument())
+    if (!inShadowIncludingDocument())
         return;
 
     // Before we give up and use fallback content, check to see if this is a MIME type issue.
diff --git a/third_party/WebKit/Source/core/html/HTMLPlugInElement.cpp b/third_party/WebKit/Source/core/html/HTMLPlugInElement.cpp
index ada27e9..993d2f6 100644
--- a/third_party/WebKit/Source/core/html/HTMLPlugInElement.cpp
+++ b/third_party/WebKit/Source/core/html/HTMLPlugInElement.cpp
@@ -269,7 +269,7 @@
         return;
 
     setNeedsWidgetUpdate(true);
-    if (inDocument())
+    if (inShadowIncludingDocument())
         lazyReattachIfNeeded();
 }
 
diff --git a/third_party/WebKit/Source/core/html/HTMLScriptElement.cpp b/third_party/WebKit/Source/core/html/HTMLScriptElement.cpp
index 0aa5a91..40486f3 100644
--- a/third_party/WebKit/Source/core/html/HTMLScriptElement.cpp
+++ b/third_party/WebKit/Source/core/html/HTMLScriptElement.cpp
@@ -90,7 +90,7 @@
 
 Node::InsertionNotificationRequest HTMLScriptElement::insertedInto(ContainerNode* insertionPoint)
 {
-    if (insertionPoint->inDocument() && hasSourceAttribute() && !loader()->isScriptTypeSupported(ScriptLoader::DisallowLegacyTypeInTypeAttribute))
+    if (insertionPoint->inShadowIncludingDocument() && hasSourceAttribute() && !loader()->isScriptTypeSupported(ScriptLoader::DisallowLegacyTypeInTypeAttribute))
         UseCounter::count(document(), UseCounter::ScriptElementWithInvalidTypeHasSrc);
     HTMLElement::insertedInto(insertionPoint);
     logAddElementIfIsolatedWorldAndInDocument("script", srcAttr);
diff --git a/third_party/WebKit/Source/core/html/HTMLSelectElement.cpp b/third_party/WebKit/Source/core/html/HTMLSelectElement.cpp
index 1c2af0e..f6d1a5b 100644
--- a/third_party/WebKit/Source/core/html/HTMLSelectElement.cpp
+++ b/third_party/WebKit/Source/core/html/HTMLSelectElement.cpp
@@ -784,7 +784,7 @@
 
     m_shouldRecalcListItems = true;
     setOptionsChangedOnLayoutObject();
-    if (!inDocument()) {
+    if (!inShadowIncludingDocument()) {
         if (HTMLOptionsCollection* collection = cachedCollection<HTMLOptionsCollection>(SelectOptions))
             collection->invalidateCache();
         invalidateSelectedItems();
@@ -946,7 +946,7 @@
 void HTMLSelectElement::scrollToOptionTask()
 {
     RawPtr<HTMLOptionElement> option = m_optionToScrollTo.release();
-    if (!option || !inDocument())
+    if (!option || !inShadowIncludingDocument())
         return;
     // optionRemoved() makes sure m_optionToScrollTo doesn't have an option with
     // another owner.
diff --git a/third_party/WebKit/Source/core/html/HTMLShadowElement.cpp b/third_party/WebKit/Source/core/html/HTMLShadowElement.cpp
index c1d65e6..fcffbb5e 100644
--- a/third_party/WebKit/Source/core/html/HTMLShadowElement.cpp
+++ b/third_party/WebKit/Source/core/html/HTMLShadowElement.cpp
@@ -68,7 +68,7 @@
 
 Node::InsertionNotificationRequest HTMLShadowElement::insertedInto(ContainerNode* insertionPoint)
 {
-    if (insertionPoint->inDocument()) {
+    if (insertionPoint->inShadowIncludingDocument()) {
         // Warn if trying to reproject between user agent and author shadows.
         ShadowRoot* root = containingShadowRoot();
         if (root && root->olderShadowRoot() && root->type() != root->olderShadowRoot()->type()) {
diff --git a/third_party/WebKit/Source/core/html/HTMLStyleElement.cpp b/third_party/WebKit/Source/core/html/HTMLStyleElement.cpp
index 439c342..40bd77c 100644
--- a/third_party/WebKit/Source/core/html/HTMLStyleElement.cpp
+++ b/third_party/WebKit/Source/core/html/HTMLStyleElement.cpp
@@ -67,7 +67,7 @@
 {
     if (name == titleAttr && m_sheet) {
         m_sheet->setTitle(value);
-    } else if (name == mediaAttr && inDocument() && document().isActive() && m_sheet) {
+    } else if (name == mediaAttr && inShadowIncludingDocument() && document().isActive() && m_sheet) {
         m_sheet->setMediaQueries(MediaQuerySet::create(value));
         document().styleEngine().setNeedsActiveStyleUpdate(m_sheet.get(), FullStyleUpdate);
     } else {
diff --git a/third_party/WebKit/Source/core/html/HTMLTextFormControlElement.cpp b/third_party/WebKit/Source/core/html/HTMLTextFormControlElement.cpp
index 469e536..1f16dd1 100644
--- a/third_party/WebKit/Source/core/html/HTMLTextFormControlElement.cpp
+++ b/third_party/WebKit/Source/core/html/HTMLTextFormControlElement.cpp
@@ -73,7 +73,7 @@
 Node::InsertionNotificationRequest HTMLTextFormControlElement::insertedInto(ContainerNode* insertionPoint)
 {
     HTMLFormControlElementWithState::insertedInto(insertionPoint);
-    if (!insertionPoint->inDocument())
+    if (!insertionPoint->inShadowIncludingDocument())
         return InsertionDone;
     String initialValue = value();
     setTextAsOfLastFormControlChangeEvent(initialValue.isNull() ? emptyString() : initialValue);
@@ -353,7 +353,7 @@
     start = std::min(std::max(start, 0), end);
     cacheSelection(start, end, direction);
 
-    if (selectionOption == NotChangeSelection || (selectionOption == ChangeSelectionIfFocused && document().focusedElement() != this) || !inDocument()) {
+    if (selectionOption == NotChangeSelection || (selectionOption == ChangeSelectionIfFocused && document().focusedElement() != this) || !inShadowIncludingDocument()) {
         if (eventBehaviour == DispatchSelectEvent)
             scheduleSelectEvent();
         return;
diff --git a/third_party/WebKit/Source/core/html/HTMLTitleElement.cpp b/third_party/WebKit/Source/core/html/HTMLTitleElement.cpp
index 4466142..b1ad2250 100644
--- a/third_party/WebKit/Source/core/html/HTMLTitleElement.cpp
+++ b/third_party/WebKit/Source/core/html/HTMLTitleElement.cpp
@@ -46,7 +46,7 @@
 Node::InsertionNotificationRequest HTMLTitleElement::insertedInto(ContainerNode* insertionPoint)
 {
     HTMLElement::insertedInto(insertionPoint);
-    if (inDocument() && !isInShadowTree())
+    if (inShadowIncludingDocument() && !isInShadowTree())
         document().setTitleElement(this);
     return InsertionDone;
 }
@@ -54,14 +54,14 @@
 void HTMLTitleElement::removedFrom(ContainerNode* insertionPoint)
 {
     HTMLElement::removedFrom(insertionPoint);
-    if (insertionPoint->inDocument() && !insertionPoint->isInShadowTree())
+    if (insertionPoint->inShadowIncludingDocument() && !insertionPoint->isInShadowTree())
         document().removeTitle(this);
 }
 
 void HTMLTitleElement::childrenChanged(const ChildrenChange& change)
 {
     HTMLElement::childrenChanged(change);
-    if (inDocument() && !isInShadowTree() && !m_ignoreTitleUpdatesWhenChildrenChange)
+    if (inShadowIncludingDocument() && !isInShadowTree() && !m_ignoreTitleUpdatesWhenChildrenChange)
         document().setTitleElement(this);
 }
 
diff --git a/third_party/WebKit/Source/core/html/forms/FormController.cpp b/third_party/WebKit/Source/core/html/forms/FormController.cpp
index 1de236f..fecdd450 100644
--- a/third_party/WebKit/Source/core/html/forms/FormController.cpp
+++ b/third_party/WebKit/Source/core/html/forms/FormController.cpp
@@ -414,7 +414,7 @@
     OwnPtr<SavedFormStateMap> stateMap = adoptPtr(new SavedFormStateMap);
     for (const auto& formControl : m_formControls) {
         HTMLFormControlElementWithState* control = formControl.get();
-        ASSERT(control->inDocument());
+        ASSERT(control->inShadowIncludingDocument());
         if (!control->shouldSaveAndRestoreFormControlState())
             continue;
         SavedFormStateMap::AddResult result = stateMap->add(keyGenerator->formKey(*control), nullptr);
diff --git a/third_party/WebKit/Source/core/html/imports/LinkImport.cpp b/third_party/WebKit/Source/core/html/imports/LinkImport.cpp
index 035c112..e4d49b5 100644
--- a/third_party/WebKit/Source/core/html/imports/LinkImport.cpp
+++ b/third_party/WebKit/Source/core/html/imports/LinkImport.cpp
@@ -62,7 +62,7 @@
 
 Document* LinkImport::importedDocument() const
 {
-    if (!m_child || !m_owner || !m_owner->inDocument())
+    if (!m_child || !m_owner || !m_owner->inShadowIncludingDocument())
         return nullptr;
     if (m_child->loader()->hasError())
         return nullptr;
@@ -101,7 +101,7 @@
 
 void LinkImport::didFinish()
 {
-    if (!m_owner || !m_owner->inDocument())
+    if (!m_owner || !m_owner->inShadowIncludingDocument())
         return;
     m_owner->scheduleEvent();
 }
diff --git a/third_party/WebKit/Source/core/html/shadow/MediaControlElements.cpp b/third_party/WebKit/Source/core/html/shadow/MediaControlElements.cpp
index 98196c1..8abd84b 100644
--- a/third_party/WebKit/Source/core/html/shadow/MediaControlElements.cpp
+++ b/third_party/WebKit/Source/core/html/shadow/MediaControlElements.cpp
@@ -397,7 +397,7 @@
     if (event->isMouseEvent() && toMouseEvent(event)->button() != LeftButton)
         return;
 
-    if (!inDocument() || !document().isActive())
+    if (!inShadowIncludingDocument() || !document().isActive())
         return;
 
     if (event->type() == EventTypeNames::mousedown)
@@ -426,7 +426,7 @@
 
 bool MediaControlTimelineElement::willRespondToMouseClickEvents()
 {
-    return inDocument() && document().isActive();
+    return inShadowIncludingDocument() && document().isActive();
 }
 
 void MediaControlTimelineElement::setPosition(double currentTime)
@@ -473,7 +473,7 @@
     if (event->isMouseEvent() && toMouseEvent(event)->button() != LeftButton)
         return;
 
-    if (!inDocument() || !document().isActive())
+    if (!inShadowIncludingDocument() || !document().isActive())
         return;
 
     MediaControlInputElement::defaultEventHandler(event);
@@ -488,7 +488,7 @@
 
 bool MediaControlVolumeSliderElement::willRespondToMouseMoveEvents()
 {
-    if (!inDocument() || !document().isActive())
+    if (!inShadowIncludingDocument() || !document().isActive())
         return false;
 
     return MediaControlInputElement::willRespondToMouseMoveEvents();
@@ -496,7 +496,7 @@
 
 bool MediaControlVolumeSliderElement::willRespondToMouseClickEvents()
 {
-    if (!inDocument() || !document().isActive())
+    if (!inShadowIncludingDocument() || !document().isActive())
         return false;
 
     return MediaControlInputElement::willRespondToMouseClickEvents();
diff --git a/third_party/WebKit/Source/core/html/track/vtt/VTTParser.cpp b/third_party/WebKit/Source/core/html/track/vtt/VTTParser.cpp
index d3acf73..811fbaf0 100644
--- a/third_party/WebKit/Source/core/html/track/vtt/VTTParser.cpp
+++ b/third_party/WebKit/Source/core/html/track/vtt/VTTParser.cpp
@@ -561,6 +561,7 @@
 DEFINE_TRACE(VTTParser)
 {
     visitor->trace(m_document);
+    visitor->trace(m_client);
     visitor->trace(m_cueList);
     visitor->trace(m_regionList);
 }
diff --git a/third_party/WebKit/Source/core/html/track/vtt/VTTParser.h b/third_party/WebKit/Source/core/html/track/vtt/VTTParser.h
index ae9b24d..262d001 100644
--- a/third_party/WebKit/Source/core/html/track/vtt/VTTParser.h
+++ b/third_party/WebKit/Source/core/html/track/vtt/VTTParser.h
@@ -47,13 +47,15 @@
 class Document;
 class VTTScanner;
 
-class VTTParserClient {
+class VTTParserClient : public GarbageCollectedMixin {
 public:
     virtual ~VTTParserClient() { }
 
     virtual void newCuesParsed() = 0;
     virtual void newRegionsParsed() = 0;
     virtual void fileFailedToParse() = 0;
+
+    DEFINE_INLINE_VIRTUAL_TRACE() { }
 };
 
 class VTTParser final : public GarbageCollectedFinalized<VTTParser> {
@@ -144,7 +146,7 @@
     StringBuilder m_currentContent;
     String m_currentSettings;
 
-    VTTParserClient* m_client;
+    Member<VTTParserClient> m_client;
 
     HeapVector<Member<TextTrackCue>> m_cueList;
 
diff --git a/third_party/WebKit/Source/core/imagebitmap/ImageBitmapFactories.cpp b/third_party/WebKit/Source/core/imagebitmap/ImageBitmapFactories.cpp
index c65872f0..2bda28d2 100644
--- a/third_party/WebKit/Source/core/imagebitmap/ImageBitmapFactories.cpp
+++ b/third_party/WebKit/Source/core/imagebitmap/ImageBitmapFactories.cpp
@@ -249,9 +249,9 @@
         m_cropRect = IntRect(IntPoint(), image->size());
     }
 
-    RawPtr<ImageBitmap> imageBitmap = ImageBitmap::create(image, m_cropRect, m_options);
+    ImageBitmap* imageBitmap = ImageBitmap::create(image, m_cropRect, m_options);
     if (imageBitmap && imageBitmap->bitmapImage()) {
-        m_resolver->resolve(imageBitmap.release());
+        m_resolver->resolve(imageBitmap);
     } else {
         rejectPromise();
         return;
diff --git a/third_party/WebKit/Source/core/imagebitmap/ImageBitmapSource.cpp b/third_party/WebKit/Source/core/imagebitmap/ImageBitmapSource.cpp
index d194467..850e3627 100644
--- a/third_party/WebKit/Source/core/imagebitmap/ImageBitmapSource.cpp
+++ b/third_party/WebKit/Source/core/imagebitmap/ImageBitmapSource.cpp
@@ -9,7 +9,7 @@
 
 namespace blink {
 
-ScriptPromise ImageBitmapSource::fulfillImageBitmap(ScriptState* scriptState, RawPtr<ImageBitmap> imageBitmap)
+ScriptPromise ImageBitmapSource::fulfillImageBitmap(ScriptState* scriptState, ImageBitmap* imageBitmap)
 {
     ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState);
     ScriptPromise promise = resolver->promise();
diff --git a/third_party/WebKit/Source/core/imagebitmap/ImageBitmapSource.h b/third_party/WebKit/Source/core/imagebitmap/ImageBitmapSource.h
index bf2a173..4e15f7f 100644
--- a/third_party/WebKit/Source/core/imagebitmap/ImageBitmapSource.h
+++ b/third_party/WebKit/Source/core/imagebitmap/ImageBitmapSource.h
@@ -24,7 +24,7 @@
 
     virtual bool isBlob() const { return false; }
 
-    static ScriptPromise fulfillImageBitmap(ScriptState*, RawPtr<ImageBitmap>);
+    static ScriptPromise fulfillImageBitmap(ScriptState*, ImageBitmap*);
 protected:
     virtual ~ImageBitmapSource() {}
 };
diff --git a/third_party/WebKit/Source/core/input/EventHandler.cpp b/third_party/WebKit/Source/core/input/EventHandler.cpp
index e3cfaf7c..f0ab67f 100644
--- a/third_party/WebKit/Source/core/input/EventHandler.cpp
+++ b/third_party/WebKit/Source/core/input/EventHandler.cpp
@@ -394,7 +394,7 @@
 
 void EventHandler::nodeWillBeRemoved(Node& nodeToBeRemoved)
 {
-    if (nodeToBeRemoved.containsIncludingShadowDOM(m_clickNode.get())) {
+    if (nodeToBeRemoved.isShadowIncludingInclusiveAncestorOf(m_clickNode.get())) {
         // We don't dispatch click events if the mousedown node is removed
         // before a mouseup event. It is compatible with IE and Firefox.
         m_clickNode = nullptr;
@@ -991,8 +991,6 @@
     if (mouseEvent.button() == NoButton)
         return WebInputEventResult::HandledSuppressed;
 
-    RawPtr<FrameView> protector(m_frame->view());
-
     UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture);
     m_frame->localFrameRoot()->eventHandler().m_lastMouseDownUserGestureToken = gestureIndicator.currentToken();
 
@@ -1027,9 +1025,9 @@
     m_mousePressNode = mev.innerNode();
     m_frame->document()->setSequentialFocusNavigationStartingPoint(mev.innerNode());
 
-    RawPtr<LocalFrame> subframe = subframeForHitTestResult(mev);
+    LocalFrame* subframe = subframeForHitTestResult(mev);
     if (subframe) {
-        WebInputEventResult result = passMousePressEventToSubframe(mev, subframe.get());
+        WebInputEventResult result = passMousePressEventToSubframe(mev, subframe);
         // Start capturing future events for this frame.  We only do this if we didn't clear
         // the m_mousePressed flag, which may happen if an AppKit widget entered a modal event loop.
         // The capturing should be done only when the result indicates it
@@ -1153,8 +1151,6 @@
 {
     TRACE_EVENT0("blink", "EventHandler::handleMouseMoveEvent");
 
-    RawPtr<FrameView> protector(m_frame->view());
-
     HitTestResult hoveredNode = HitTestResult();
     WebInputEventResult result = handleMouseMoveOrLeaveEvent(event, &hoveredNode);
 
@@ -1180,7 +1176,6 @@
 {
     TRACE_EVENT0("blink", "EventHandler::handleMouseLeaveEvent");
 
-    RawPtr<FrameView> protector(m_frame->view());
     handleMouseMoveOrLeaveEvent(event, 0, false, true);
 }
 
@@ -1256,7 +1251,7 @@
     }
 
     WebInputEventResult eventResult = WebInputEventResult::NotHandled;
-    RawPtr<LocalFrame> newSubframe = m_capturingMouseEventsNode.get() ? subframeForTargetNode(m_capturingMouseEventsNode.get()) : subframeForHitTestResult(mev);
+    LocalFrame* newSubframe = m_capturingMouseEventsNode.get() ? subframeForTargetNode(m_capturingMouseEventsNode.get()) : subframeForHitTestResult(mev);
 
     // We want mouseouts to happen first, from the inside out.  First send a move event to the last subframe so that it will fire mouseouts.
     if (m_lastMouseMoveEventSubframe && m_lastMouseMoveEventSubframe->tree().isDescendantOf(m_frame) && m_lastMouseMoveEventSubframe != newSubframe)
@@ -1269,7 +1264,7 @@
         // Event dispatch in updateMouseEventTargetNodeAndSendEvents may have caused the subframe of the target
         // node to be detached from its FrameView, in which case the event should not be passed.
         if (newSubframe->view())
-            eventResult = passMouseMoveEventToSubframe(mev, newSubframe.get(), hoveredNode);
+            eventResult = passMouseMoveEventToSubframe(mev, newSubframe, hoveredNode);
     } else {
         if (scrollbar && !m_mousePressed)
             scrollbar->mouseMoved(mev.event()); // Handle hover effects on platforms that support visual feedback on scrollbar hovering.
@@ -1319,8 +1314,6 @@
     if (mouseEvent.button() == NoButton)
         return WebInputEventResult::HandledSuppressed;
 
-    RawPtr<FrameView> protector(m_frame->view());
-
     m_frame->selection().setCaretBlinkingSuspended(false);
 
     OwnPtr<UserGestureIndicator> gestureIndicator;
@@ -1420,14 +1413,14 @@
     if (!view)
         return WebInputEventResult::NotHandled;
 
-    RawPtr<DragEvent> me = DragEvent::create(eventType,
+    DragEvent* me = DragEvent::create(eventType,
         true, true, m_frame->document()->domWindow(),
         0, event.globalPosition().x(), event.globalPosition().y(), event.position().x(), event.position().y(),
         event.movementDelta().x(), event.movementDelta().y(),
         event.getModifiers(),
         0, MouseEvent::platformModifiersToButtons(event.getModifiers()), nullptr, event.timestamp(), dataTransfer, event.getSyntheticEventType());
 
-    return toWebInputEventResult(dragTarget->dispatchEvent(me.get()));
+    return toWebInputEventResult(dragTarget->dispatchEvent(me));
 }
 
 static bool targetIsFrame(Node* target, LocalFrame*& frame)
@@ -1493,12 +1486,12 @@
     MouseEventWithHitTestResults mev = prepareMouseEvent(request, event);
 
     // Drag events should never go to text nodes (following IE, and proper mouseover/out dispatch)
-    RawPtr<Node> newTarget = mev.innerNode();
+    Node* newTarget = mev.innerNode();
     if (newTarget && newTarget->isTextNode())
         newTarget = FlatTreeTraversal::parent(*newTarget);
 
     if (AutoscrollController* controller = autoscrollController())
-        controller->updateDragAndDrop(newTarget.get(), event.position(), event.timestamp());
+        controller->updateDragAndDrop(newTarget, event.position(), event.timestamp());
 
     if (m_dragTarget != newTarget) {
         // FIXME: this ordering was explicitly chosen to match WinIE. However,
@@ -1507,7 +1500,7 @@
         //
         // Moreover, this ordering conforms to section 7.9.4 of the HTML 5 spec. <http://dev.w3.org/html5/spec/Overview.html#drag-and-drop-processing-model>.
         LocalFrame* targetFrame;
-        if (targetIsFrame(newTarget.get(), targetFrame)) {
+        if (targetIsFrame(newTarget, targetFrame)) {
             if (targetFrame)
                 eventResult = targetFrame->eventHandler().updateDragAndDrop(event, dataTransfer);
         } else if (newTarget) {
@@ -1516,8 +1509,8 @@
                 // for now we don't care if event handler cancels default behavior, since there is none
                 dispatchDragSrcEvent(EventTypeNames::drag, event);
             }
-            eventResult = dispatchDragEvent(EventTypeNames::dragenter, newTarget.get(), event, dataTransfer);
-            if (eventResult == WebInputEventResult::NotHandled && findDropZone(newTarget.get(), dataTransfer))
+            eventResult = dispatchDragEvent(EventTypeNames::dragenter, newTarget, event, dataTransfer);
+            if (eventResult == WebInputEventResult::NotHandled && findDropZone(newTarget, dataTransfer))
                 eventResult = WebInputEventResult::HandledSystem;
         }
 
@@ -1535,7 +1528,7 @@
         }
     } else {
         LocalFrame* targetFrame;
-        if (targetIsFrame(newTarget.get(), targetFrame)) {
+        if (targetIsFrame(newTarget, targetFrame)) {
             if (targetFrame)
                 eventResult = targetFrame->eventHandler().updateDragAndDrop(event, dataTransfer);
         } else if (newTarget) {
@@ -1544,8 +1537,8 @@
                 // for now we don't care if event handler cancels default behavior, since there is none
                 dispatchDragSrcEvent(EventTypeNames::drag, event);
             }
-            eventResult = dispatchDragEvent(EventTypeNames::dragover, newTarget.get(), event, dataTransfer);
-            if (eventResult == WebInputEventResult::NotHandled && findDropZone(newTarget.get(), dataTransfer))
+            eventResult = dispatchDragEvent(EventTypeNames::dragover, newTarget, event, dataTransfer);
+            if (eventResult == WebInputEventResult::NotHandled && findDropZone(newTarget, dataTransfer))
                 eventResult = WebInputEventResult::HandledSystem;
             m_shouldOnlyFireDragOverEvent = false;
         }
@@ -1591,7 +1584,7 @@
     m_shouldOnlyFireDragOverEvent = false;
 }
 
-void EventHandler::setCapturingMouseEventsNode(RawPtr<Node> n)
+void EventHandler::setCapturingMouseEventsNode(Node* n)
 {
     m_capturingMouseEventsNode = n;
     m_eventHandlerWillResetCapturingMouseEventsNode = false;
@@ -1605,7 +1598,7 @@
     return m_frame->document()->prepareMouseEvent(request, contentPointFromRootFrame(m_frame, mev.position()), mev);
 }
 
-RawPtr<Node> EventHandler::updateMouseEventTargetNode(Node* targetNode,
+Node* EventHandler::updateMouseEventTargetNode(Node* targetNode,
     const PlatformMouseEvent& mouseEvent)
 {
     Node* result = targetNode;
@@ -1618,10 +1611,10 @@
         if (result && result->isTextNode())
             result = FlatTreeTraversal::parent(*result);
     }
-    Member<Node> lastNodeUnderMouse = m_nodeUnderMouse;
+    Node* lastNodeUnderMouse = m_nodeUnderMouse;
     m_nodeUnderMouse = result;
 
-    PaintLayer* layerForLastNode = layerForNode(lastNodeUnderMouse.get());
+    PaintLayer* layerForLastNode = layerForNode(lastNodeUnderMouse);
     PaintLayer* layerForNodeUnderMouse = layerForNode(m_nodeUnderMouse.get());
     Page* page = m_frame->page();
 
@@ -1660,7 +1653,7 @@
 void EventHandler::updateMouseEventTargetNodeAndSendEvents(Node* targetNode,
     const PlatformMouseEvent& mouseEvent, bool isFrameBoundaryTransition)
 {
-    RawPtr<Node> lastNodeUnderMouse = updateMouseEventTargetNode(targetNode, mouseEvent);
+    Node* lastNodeUnderMouse = updateMouseEventTargetNode(targetNode, mouseEvent);
     m_pointerEventManager.sendMouseAndPossiblyPointerNodeTransitionEvents(
         lastNodeUnderMouse, m_nodeUnderMouse, mouseEvent,
         m_frame->document()->domWindow(), isFrameBoundaryTransition);
@@ -1672,7 +1665,7 @@
     if (!m_nodeUnderMouse)
         return WebInputEventResult::NotHandled;
 
-    RawPtr<MouseEvent> event = MouseEvent::create(eventType, m_nodeUnderMouse->document().domWindow(), mouseEvent, clickCount, nullptr);
+    MouseEvent* event = MouseEvent::create(eventType, m_nodeUnderMouse->document().domWindow(), mouseEvent, clickCount, nullptr);
     return toWebInputEventResult(m_nodeUnderMouse->dispatchEvent(event));
 }
 
@@ -1709,7 +1702,7 @@
         || mouseEventType == EventTypeNames::mousemove
         || mouseEventType == EventTypeNames::mouseup);
 
-    RawPtr<Node> lastNodeUnderMouse = updateMouseEventTargetNode(targetNode, mouseEvent);
+    Node* lastNodeUnderMouse = updateMouseEventTargetNode(targetNode, mouseEvent);
 
     return m_pointerEventManager.sendMousePointerEvent(
         m_nodeUnderMouse, mouseEventType, clickCount, mouseEvent, nullptr,
@@ -1783,7 +1776,7 @@
 {
     if (element.authorShadowRoot() && element.authorShadowRoot()->delegatesFocus()) {
         Document* doc = m_frame->document();
-        if (element.containsIncludingShadowDOM(doc->focusedElement())) {
+        if (element.isShadowIncludingInclusiveAncestorOf(doc->focusedElement())) {
             // If the inner element is already focused, do nothing.
             return true;
         }
@@ -1792,7 +1785,7 @@
         Page* page = m_frame->page();
         ASSERT(page);
         Element* found = page->focusController().findFocusableElementInShadowHost(element);
-        if (found && element.containsIncludingShadowDOM(found)) {
+        if (found && element.isShadowIncludingInclusiveAncestorOf(found)) {
             // Use WebFocusTypeForward instead of WebFocusTypeMouse here to mean the focus has slided.
             found->focus(FocusParams(SelectionBehaviorOnFocus::Reset, WebFocusTypeForward, nullptr));
             return true;
@@ -1808,8 +1801,6 @@
     if (!doc->layoutView())
         return WebInputEventResult::NotHandled;
 
-    RawPtr<FrameView> protector(m_frame->view());
-
     FrameView* view = m_frame->view();
     if (!view)
         return WebInputEventResult::NotHandled;
@@ -1846,13 +1837,13 @@
     }
 
     if (node) {
-        RawPtr<WheelEvent> domEvent = WheelEvent::create(event, node->document().domWindow());
+        WheelEvent* domEvent = WheelEvent::create(event, node->document().domWindow());
         if (sendDOMEvent) {
             DispatchEventResult domEventResult = node->dispatchEvent(domEvent);
             if (domEventResult != DispatchEventResult::NotCanceled)
                 return toWebInputEventResult(domEventResult);
         } else {
-            defaultWheelEventHandler(node, domEvent.get());
+            defaultWheelEventHandler(node, domEvent);
             if (domEvent->defaultHandled())
                 return WebInputEventResult::HandledSystem;
         }
@@ -1906,7 +1897,7 @@
     if (consumed)
         wheelEvent->setDefaultHandled();
 
-    if (m_frame->isMainFrame() && m_frame->settings() && m_frame->settings()->reportWheelOverscroll())
+    if (m_frame->isMainFrame())
         handleOverscroll(result);
 }
 
@@ -1974,8 +1965,8 @@
 {
     ASSERT(!targetedEvent.event().isScrollEvent());
 
-    RawPtr<Node> eventTarget = targetedEvent.hitTestResult().innerNode();
-    RawPtr<Scrollbar> scrollbar = targetedEvent.hitTestResult().scrollbar();
+    Node* eventTarget = targetedEvent.hitTestResult().innerNode();
+    Scrollbar* scrollbar = targetedEvent.hitTestResult().scrollbar();
     const PlatformGestureEvent& gestureEvent = targetedEvent.event();
 
     if (scrollbar) {
@@ -1988,8 +1979,8 @@
     }
 
     if (eventTarget) {
-        RawPtr<GestureEvent> gestureDomEvent = GestureEvent::create(eventTarget->document().domWindow(), gestureEvent);
-        if (gestureDomEvent.get()) {
+        GestureEvent* gestureDomEvent = GestureEvent::create(eventTarget->document().domWindow(), gestureEvent);
+        if (gestureDomEvent) {
             DispatchEventResult gestureDomEventResult = eventTarget->dispatchEvent(gestureDomEvent);
             if (gestureDomEventResult != DispatchEventResult::NotCanceled) {
                 ASSERT(gestureDomEventResult != DispatchEventResult::CanceledByEventHandler);
@@ -2027,8 +2018,8 @@
 {
     TRACE_EVENT0("input", "EventHandler::handleGestureScrollEvent");
 
-    RawPtr<Node> eventTarget = nullptr;
-    RawPtr<Scrollbar> scrollbar = nullptr;
+    Node* eventTarget = nullptr;
+    Scrollbar* scrollbar = nullptr;
     if (gestureEvent.type() != PlatformEvent::GestureScrollBegin) {
         scrollbar = m_scrollbarHandlingScrollGesture.get();
         eventTarget = m_scrollGestureHandlingNode.get();
@@ -2066,11 +2057,11 @@
     }
 
     if (eventTarget) {
-        if (handleScrollGestureOnResizer(eventTarget.get(), gestureEvent))
+        if (handleScrollGestureOnResizer(eventTarget, gestureEvent))
             return WebInputEventResult::HandledSuppressed;
 
-        RawPtr<GestureEvent> gestureDomEvent = GestureEvent::create(eventTarget->document().domWindow(), gestureEvent);
-        if (gestureDomEvent.get()) {
+        GestureEvent* gestureDomEvent = GestureEvent::create(eventTarget->document().domWindow(), gestureEvent);
+        if (gestureDomEvent) {
             DispatchEventResult gestureDomEventResult = eventTarget->dispatchEvent(gestureDomEvent);
             if (gestureDomEventResult != DispatchEventResult::NotCanceled) {
                 ASSERT(gestureDomEventResult != DispatchEventResult::CanceledByEventHandler);
@@ -2099,7 +2090,7 @@
 
 WebInputEventResult EventHandler::handleGestureTap(const GestureEventWithHitTestResults& targetedEvent)
 {
-    RawPtr<FrameView> frameView(m_frame->view());
+    FrameView* frameView(m_frame->view());
     const PlatformGestureEvent& gestureEvent = targetedEvent.event();
     HitTestRequest::HitTestRequestType hitType = getHitTypeForGestureType(gestureEvent.type());
     uint64_t preDispatchDomTreeVersion = m_frame->document()->domTreeVersion();
@@ -2137,7 +2128,7 @@
     m_clickNode = currentHitTest.innerNode();
 
     // Capture data for showUnhandledTapUIIfNeeded.
-    RawPtr<Node> tappedNode = m_clickNode;
+    Node* tappedNode = m_clickNode;
     IntPoint tappedPosition = gestureEvent.position();
 
     if (m_clickNode && m_clickNode->isTextNode())
@@ -2199,7 +2190,7 @@
         bool styleChanged = preDispatchStyleVersion != m_frame->document()->styleVersion();
 
         IntPoint tappedPositionInViewport = m_frame->page()->frameHost().visualViewport().rootFrameToViewport(tappedPosition);
-        m_frame->chromeClient().showUnhandledTapUIIfNeeded(tappedPositionInViewport, tappedNode.get(), domTreeChanged || styleChanged);
+        m_frame->chromeClient().showUnhandledTapUIIfNeeded(tappedPositionInViewport, tappedNode, domTreeChanged || styleChanged);
     }
     return eventResult;
 }
@@ -2230,7 +2221,6 @@
         m_mouseDownMayStartDrag = true;
         dragState().m_dragSrc = nullptr;
         m_mouseDownPos = m_frame->view()->rootFrameToContents(mouseDragEvent.position());
-        RawPtr<FrameView> protector(m_frame->view());
         if (handleDrag(mev, DragInitiator::Touch)) {
             m_longTapShouldInvokeContextMenu = true;
             return WebInputEventResult::HandledSystem;
@@ -2239,7 +2229,6 @@
 
     IntPoint hitTestPoint = m_frame->view()->rootFrameToContents(gestureEvent.position());
     HitTestResult result = hitTestResultAtPoint(hitTestPoint);
-    RawPtr<FrameView> protector(m_frame->view());
     if (selectionController().handleGestureLongPress(gestureEvent, result)) {
         focusDocumentView();
         return WebInputEventResult::HandledSystem;
@@ -2303,7 +2292,7 @@
 
 WebInputEventResult EventHandler::handleGestureScrollEnd(const PlatformGestureEvent& gestureEvent)
 {
-    RawPtr<Node> node = m_scrollGestureHandlingNode;
+    Node* node = m_scrollGestureHandlingNode;
 
     if (node) {
         passScrollGestureEventToWidget(gestureEvent, node->layoutObject());
@@ -2314,8 +2303,8 @@
             scrollStateData->from_user_input = true;
             scrollStateData->is_direct_manipulation = true;
             scrollStateData->delta_consumed_for_scroll_sequence = m_deltaConsumedForScrollSequence;
-            RawPtr<ScrollState> scrollState = ScrollState::create(scrollStateData.release());
-            customizedScroll(*node.get(), *scrollState);
+            ScrollState* scrollState = ScrollState::create(scrollStateData.release());
+            customizedScroll(*node, *scrollState);
         }
     }
 
@@ -2355,7 +2344,7 @@
         scrollStateData->is_beginning = true;
         scrollStateData->from_user_input = true;
         scrollStateData->delta_consumed_for_scroll_sequence = m_deltaConsumedForScrollSequence;
-        RawPtr<ScrollState> scrollState = ScrollState::create(scrollStateData.release());
+        ScrollState* scrollState = ScrollState::create(scrollStateData.release());
         customizedScroll(*m_scrollGestureHandlingNode.get(), *scrollState);
     } else {
         if (m_frame->isMainFrame())
@@ -2418,8 +2407,6 @@
         if (!layoutObject)
             return WebInputEventResult::NotHandled;
 
-        RawPtr<FrameView> protector(m_frame->view());
-
         // Try to send the event to the correct view.
         WebInputEventResult result = passScrollGestureEventToWidget(gestureEvent, layoutObject);
         if (result != WebInputEventResult::NotHandled) {
@@ -2445,7 +2432,7 @@
             scrollStateData->is_in_inertial_phase = gestureEvent.inertial();
             scrollStateData->from_user_input = true;
             scrollStateData->delta_consumed_for_scroll_sequence = m_deltaConsumedForScrollSequence;
-            RawPtr<ScrollState> scrollState = ScrollState::create(scrollStateData.release());
+            ScrollState* scrollState = ScrollState::create(scrollStateData.release());
             if (m_previousGestureScrolledNode) {
                 // The ScrollState needs to know what the current
                 // native scrolling element is, so that for an
@@ -2582,8 +2569,8 @@
         newHoverFrameInDocument = parentFrame && parentFrame->isLocalFrame() ? toLocalFrame(parentFrame) : nullptr;
     }
 
-    RawPtr<Node> oldHoverNodeInCurDoc = m_frame->document()->hoverNode();
-    RawPtr<Node> newInnermostHoverNode = innerElement;
+    Node* oldHoverNodeInCurDoc = m_frame->document()->hoverNode();
+    Node* newInnermostHoverNode = innerElement;
 
     if (newInnermostHoverNode != oldHoverNodeInCurDoc) {
         size_t indexFrameChain = newHoverFrameChain.size();
@@ -2596,7 +2583,7 @@
             if (indexFrameChain > 0)
                 newHoverFrame = newHoverFrameChain[--indexFrameChain];
 
-            HTMLFrameOwnerElement* owner = toHTMLFrameOwnerElement(oldHoverNodeInCurDoc.get());
+            HTMLFrameOwnerElement* owner = toHTMLFrameOwnerElement(oldHoverNodeInCurDoc);
             if (!owner->contentFrame() || !owner->contentFrame()->isLocalFrame())
                 break;
 
@@ -3103,7 +3090,6 @@
 
 WebInputEventResult EventHandler::keyEvent(const PlatformKeyboardEvent& initialKeyEvent)
 {
-    RawPtr<FrameView> protector(m_frame->view());
     m_frame->chromeClient().clearToolTip();
 
     if (initialKeyEvent.windowsVirtualKeyCode() == VK_CAPITAL)
@@ -3122,7 +3108,7 @@
 
     // Check for cases where we are too early for events -- possible unmatched key up
     // from pressing return in the location bar.
-    RawPtr<Node> node = eventTargetNodeForDocument(m_frame->document());
+    Node* node = eventTargetNodeForDocument(m_frame->document());
     if (!node)
         return WebInputEventResult::NotHandled;
 
@@ -3139,7 +3125,7 @@
 
     // FIXME: it would be fair to let an input method handle KeyUp events before DOM dispatch.
     if (initialKeyEvent.type() == PlatformEvent::KeyUp || initialKeyEvent.type() == PlatformEvent::Char) {
-        RawPtr<KeyboardEvent> domEvent = KeyboardEvent::create(initialKeyEvent, m_frame->document()->domWindow());
+        KeyboardEvent* domEvent = KeyboardEvent::create(initialKeyEvent, m_frame->document()->domWindow());
 
         return toWebInputEventResult(node->dispatchEvent(domEvent));
     }
@@ -3147,7 +3133,7 @@
     PlatformKeyboardEvent keyDownEvent = initialKeyEvent;
     if (keyDownEvent.type() != PlatformEvent::RawKeyDown)
         keyDownEvent.disambiguateKeyDownEvent(PlatformEvent::RawKeyDown);
-    RawPtr<KeyboardEvent> keydown = KeyboardEvent::create(keyDownEvent, m_frame->document()->domWindow());
+    KeyboardEvent* keydown = KeyboardEvent::create(keyDownEvent, m_frame->document()->domWindow());
     if (matchedAnAccessKey)
         keydown->setDefaultPrevented(true);
     keydown->setTarget(node);
@@ -3173,7 +3159,7 @@
     keyPressEvent.disambiguateKeyDownEvent(PlatformEvent::Char);
     if (keyPressEvent.text().isEmpty())
         return WebInputEventResult::NotHandled;
-    RawPtr<KeyboardEvent> keypress = KeyboardEvent::create(keyPressEvent, m_frame->document()->domWindow());
+    KeyboardEvent* keypress = KeyboardEvent::create(keyPressEvent, m_frame->document()->domWindow());
     keypress->setTarget(node);
     return toWebInputEventResult(node->dispatchEvent(keypress));
 }
@@ -3288,7 +3274,7 @@
 void EventHandler::updateDragStateAfterEditDragIfNeeded(Element* rootEditableElement)
 {
     // If inserting the dragged contents removed the drag source, we still want to fire dragend at the root editble element.
-    if (dragState().m_dragSrc && !dragState().m_dragSrc->inDocument())
+    if (dragState().m_dragSrc && !dragState().m_dragSrc->inShadowIncludingDocument())
         dragState().m_dragSrc = rootEditableElement;
 }
 
@@ -3417,7 +3403,7 @@
     if (!target)
         return false;
 
-    RawPtr<TextEvent> event = TextEvent::create(m_frame->domWindow(), text, inputType);
+    TextEvent* event = TextEvent::create(m_frame->domWindow(), text, inputType);
     event->setUnderlyingEvent(underlyingEvent);
 
     target->dispatchEvent(event);
@@ -3660,7 +3646,7 @@
     // lists fit together.
 
     // Holds the complete set of touches on the screen.
-    RawPtr<TouchList> touches = TouchList::create();
+    TouchList* touches = TouchList::create();
 
     // A different view on the 'touches' list above, filtered and grouped by
     // event target. Used for the 'targetTouches' list in the JS event.
@@ -3678,7 +3664,7 @@
         if (touchInfo.consumed)
             continue;
 
-        RawPtr<Touch> touch = Touch::create(
+        Touch* touch = Touch::create(
             touchInfo.targetFrame.get(),
             touchInfo.touchTarget.get(),
             point.id(),
@@ -3734,13 +3720,13 @@
 
         const AtomicString& eventName(touchEventNameForTouchPointState(static_cast<PlatformTouchPoint::TouchState>(state)));
         for (const auto& eventTarget : changedTouches[state].m_targets) {
-            EventTarget* touchEventTarget = eventTarget.get();
-            RawPtr<TouchEvent> touchEvent = TouchEvent::create(
-                touches.get(), touchesByTarget.get(touchEventTarget), changedTouches[state].m_touches.get(),
+            EventTarget* touchEventTarget = eventTarget;
+            TouchEvent* touchEvent = TouchEvent::create(
+                touches, touchesByTarget.get(touchEventTarget), changedTouches[state].m_touches.get(),
                 eventName, touchEventTarget->toNode()->document().domWindow(),
                 event.getModifiers(), event.cancelable(), event.causesScrollingIfUncanceled(), event.timestamp());
 
-            eventResult = mergeEventResult(eventResult, toWebInputEventResult(touchEventTarget->dispatchEvent(touchEvent.get())));
+            eventResult = mergeEventResult(eventResult, toWebInputEventResult(touchEventTarget->dispatchEvent(touchEvent)));
         }
     }
 
@@ -3865,7 +3851,7 @@
     for (unsigned i = 0; i < points.size(); ++i) {
         const PlatformTouchPoint& point = points[i];
         PlatformTouchPoint::TouchState pointState = point.state();
-        RawPtr<EventTarget> touchTarget = nullptr;
+        EventTarget* touchTarget = nullptr;
         String regionID;
 
         if (pointState == PlatformTouchPoint::TouchReleased || pointState == PlatformTouchPoint::TouchCancelled) {
diff --git a/third_party/WebKit/Source/core/input/EventHandler.h b/third_party/WebKit/Source/core/input/EventHandler.h
index f177b85..a6ba68b 100644
--- a/third_party/WebKit/Source/core/input/EventHandler.h
+++ b/third_party/WebKit/Source/core/input/EventHandler.h
@@ -113,7 +113,7 @@
 
     bool mousePressed() const { return m_mousePressed; }
 
-    void setCapturingMouseEventsNode(RawPtr<Node>); // A caller is responsible for resetting capturing node to 0.
+    void setCapturingMouseEventsNode(Node*); // A caller is responsible for resetting capturing node to 0.
 
     WebInputEventResult updateDragAndDrop(const PlatformMouseEvent&, DataTransfer*);
     void cancelDragAndDrop(const PlatformMouseEvent&, DataTransfer*);
@@ -312,7 +312,7 @@
 
     void invalidateClick();
 
-    RawPtr<Node> updateMouseEventTargetNode(Node*, const PlatformMouseEvent&);
+    Node* updateMouseEventTargetNode(Node*, const PlatformMouseEvent&);
     void updateMouseEventTargetNodeAndSendEvents(Node*, const PlatformMouseEvent&, bool isFrameBoundaryTransition = false);
 
 
diff --git a/third_party/WebKit/Source/core/input/PointerEventManager.cpp b/third_party/WebKit/Source/core/input/PointerEventManager.cpp
index 8b0b269f..f784bbcc 100644
--- a/third_party/WebKit/Source/core/input/PointerEventManager.cpp
+++ b/third_party/WebKit/Source/core/input/PointerEventManager.cpp
@@ -31,25 +31,23 @@
     }
 }
 
-bool isInDocument(RawPtr<EventTarget> n)
+bool isInDocument(EventTarget* n)
 {
-    return n && n->toNode() && n->toNode()->inDocument();
+    return n && n->toNode() && n->toNode()->inShadowIncludingDocument();
 }
 
 WebInputEventResult dispatchMouseEvent(
-    RawPtr<EventTarget> prpTarget,
+    EventTarget* target,
     const AtomicString& mouseEventType,
     const PlatformMouseEvent& mouseEvent,
-    RawPtr<EventTarget> prpRelatedTarget,
+    EventTarget* relatedTarget,
     int detail = 0,
     bool checkForListener = false)
 {
-    RawPtr<EventTarget> target = prpTarget;
-    RawPtr<EventTarget> relatedTarget = prpRelatedTarget;
     if (target && target->toNode()
         && (!checkForListener || target->hasEventListeners(mouseEventType))) {
-        RawPtr<Node> targetNode = target->toNode();
-        RawPtr<MouseEvent> event = MouseEvent::create(mouseEventType,
+        Node* targetNode = target->toNode();
+        MouseEvent* event = MouseEvent::create(mouseEventType,
             targetNode->document().domWindow(), mouseEvent, detail,
             relatedTarget ? relatedTarget->toNode() : nullptr);
         DispatchEventResult dispatchResult = target->dispatchEvent(event);
@@ -61,13 +59,10 @@
 } // namespace
 
 WebInputEventResult PointerEventManager::dispatchPointerEvent(
-    RawPtr<EventTarget> prpTarget,
-    RawPtr<PointerEvent> prpPointerEvent,
+    EventTarget* target,
+    PointerEvent* pointerEvent,
     bool checkForListener)
 {
-    RawPtr<EventTarget> target = prpTarget;
-    RawPtr<PointerEvent> pointerEvent = prpPointerEvent;
-
     if (!target)
         return WebInputEventResult::NotHandled;
 
@@ -77,7 +72,7 @@
     if ((eventType == EventTypeNames::pointerout
         || eventType == EventTypeNames::pointerover)
         && m_nodeUnderPointer.contains(pointerId)) {
-        RawPtr<EventTarget> targetUnderPointer =
+        EventTarget* targetUnderPointer =
             m_nodeUnderPointer.get(pointerId).target;
         if (targetUnderPointer == target) {
             m_nodeUnderPointer.set(pointerId, EventTargetAttributes
@@ -95,8 +90,8 @@
     return WebInputEventResult::NotHandled;
 }
 
-RawPtr<EventTarget> PointerEventManager::getEffectiveTargetForPointerEvent(
-    RawPtr<EventTarget> target, int pointerId)
+EventTarget* PointerEventManager::getEffectiveTargetForPointerEvent(
+    EventTarget* target, int pointerId)
 {
     if (EventTarget* capturingTarget = getCapturingNode(pointerId))
         return capturingTarget;
@@ -104,14 +99,14 @@
 }
 
 void PointerEventManager::sendMouseAndPossiblyPointerNodeTransitionEvents(
-    RawPtr<Node> exitedNode,
-    RawPtr<Node> enteredNode,
+    Node* exitedNode,
+    Node* enteredNode,
     const PlatformMouseEvent& mouseEvent,
-    RawPtr<AbstractView> view,
+    AbstractView* view,
     bool isFrameBoundaryTransition)
 {
     // Pointer event type does not matter as it will be overridden in the sendNodeTransitionEvents
-    RawPtr<PointerEvent> pointerEvent =
+    PointerEvent* pointerEvent =
         m_pointerEventFactory.create(EventTypeNames::mouseout, mouseEvent,
         nullptr, view);
 
@@ -129,15 +124,11 @@
 }
 
 void PointerEventManager::sendNodeTransitionEvents(
-    RawPtr<EventTarget> prpExitedTarget,
-    RawPtr<EventTarget> prpEnteredTarget,
-    RawPtr<PointerEvent> prpPointerEvent,
+    EventTarget* exitedTarget,
+    EventTarget* enteredTarget,
+    PointerEvent* pointerEvent,
     const PlatformMouseEvent& mouseEvent, bool sendMouseEvent)
 {
-    RawPtr<EventTarget> exitedTarget = prpExitedTarget;
-    RawPtr<EventTarget> enteredTarget = prpEnteredTarget;
-    RawPtr<PointerEvent> pointerEvent = prpPointerEvent;
-
     if (exitedTarget == enteredTarget)
         return;
 
@@ -165,16 +156,16 @@
     HeapVector<Member<Node>, 32> exitedAncestors;
     HeapVector<Member<Node>, 32> enteredAncestors;
     if (isInDocument(exitedTarget)) {
-        RawPtr<Node> exitedNode = exitedTarget->toNode();
+        Node* exitedNode = exitedTarget->toNode();
         exitedNode->updateDistribution();
-        for (RawPtr<Node> node = exitedNode; node; node = FlatTreeTraversal::parent(*node))
+        for (Node* node = exitedNode; node; node = FlatTreeTraversal::parent(*node))
             exitedAncestors.append(node);
     }
 
     if (isInDocument(enteredTarget)) {
-        RawPtr<Node> enteredNode = enteredTarget->toNode();
+        Node* enteredNode = enteredTarget->toNode();
         enteredNode->updateDistribution();
-        for (RawPtr<Node> node = enteredNode; node; node = FlatTreeTraversal::parent(*node))
+        for (Node* node = enteredNode; node; node = FlatTreeTraversal::parent(*node))
             enteredAncestors.append(node);
     }
 
@@ -268,12 +259,10 @@
 }
 
 void PointerEventManager::setNodeUnderPointer(
-    RawPtr<PointerEvent> prpPointerEvent,
-    RawPtr<EventTarget> prpTarget,
+    PointerEvent* pointerEvent,
+    EventTarget* target,
     bool sendEvent)
 {
-    RawPtr<PointerEvent> pointerEvent = prpPointerEvent;
-    RawPtr<EventTarget> target = prpTarget;
     if (m_nodeUnderPointer.contains(pointerEvent->pointerId())) {
         EventTargetAttributes node = m_nodeUnderPointer.get(
             pointerEvent->pointerId());
@@ -294,10 +283,9 @@
     }
 }
 
-void PointerEventManager::sendTouchCancelPointerEvent(RawPtr<EventTarget> prpTarget, const PlatformTouchPoint& point)
+void PointerEventManager::sendTouchCancelPointerEvent(EventTarget* target, const PlatformTouchPoint& point)
 {
-    RawPtr<EventTarget> target = prpTarget;
-    RawPtr<PointerEvent> pointerEvent = m_pointerEventFactory.createPointerCancelEvent(point);
+    PointerEvent* pointerEvent = m_pointerEventFactory.createPointerCancelEvent(point);
 
 
     processCaptureAndPositionOfPointerEvent(pointerEvent, target);
@@ -305,7 +293,7 @@
     // TODO(nzolghadr): crbug.com/579553 dealing with implicit touch capturing vs pointer event capturing
     dispatchPointerEvent(
         getEffectiveTargetForPointerEvent(target, pointerEvent->pointerId()),
-        pointerEvent.get());
+        pointerEvent);
 
     releasePointerCapture(pointerEvent->pointerId());
 
@@ -318,14 +306,12 @@
 }
 
 WebInputEventResult PointerEventManager::sendTouchPointerEvent(
-    RawPtr<EventTarget> prpTarget,
+    EventTarget* target,
     const PlatformTouchPoint& touchPoint, PlatformEvent::Modifiers modifiers,
     const double width, const double height,
     const double clientX, const double clientY)
 {
-    RawPtr<EventTarget> target = prpTarget;
-
-    RawPtr<PointerEvent> pointerEvent =
+    PointerEvent* pointerEvent =
         m_pointerEventFactory.create(
         pointerEventNameForTouchPointState(touchPoint.state()),
         touchPoint, modifiers, width, height, clientX, clientY);
@@ -335,7 +321,7 @@
     // TODO(nzolghadr): crbug.com/579553 dealing with implicit touch capturing vs pointer event capturing
     WebInputEventResult result = dispatchPointerEvent(
         getEffectiveTargetForPointerEvent(target, pointerEvent->pointerId()),
-        pointerEvent.get());
+        pointerEvent);
 
     // Setting the implicit capture for touch
     if (touchPoint.state() == PlatformTouchPoint::TouchPressed)
@@ -357,15 +343,13 @@
 }
 
 WebInputEventResult PointerEventManager::sendMousePointerEvent(
-    RawPtr<Node> prpTarget, const AtomicString& mouseEventType,
+    Node* target, const AtomicString& mouseEventType,
     int clickCount, const PlatformMouseEvent& mouseEvent,
-    RawPtr<Node> relatedTarget,
-    RawPtr<AbstractView> view,
-    RawPtr<Node> lastNodeUnderMouse)
+    Node* relatedTarget,
+    AbstractView* view,
+    Node* lastNodeUnderMouse)
 {
-    RawPtr<Node> target = prpTarget;
-
-    RawPtr<PointerEvent> pointerEvent =
+    PointerEvent* pointerEvent =
         m_pointerEventFactory.create(mouseEventType, mouseEvent,
         relatedTarget, view);
 
@@ -378,7 +362,7 @@
     processCaptureAndPositionOfPointerEvent(pointerEvent, target,
         lastNodeUnderMouse, mouseEvent, true, true);
 
-    RawPtr<EventTarget> effectiveTarget =
+    EventTarget* effectiveTarget =
         getEffectiveTargetForPointerEvent(target, pointerEvent->pointerId());
 
     WebInputEventResult result =
@@ -421,14 +405,12 @@
 }
 
 void PointerEventManager::processCaptureAndPositionOfPointerEvent(
-    const RawPtr<PointerEvent> prpPointerEvent,
-    const RawPtr<EventTarget> prpHitTestTarget,
-    const RawPtr<EventTarget> lastNodeUnderMouse,
+    PointerEvent* pointerEvent,
+    EventTarget* hitTestTarget,
+    EventTarget* lastNodeUnderMouse,
     const PlatformMouseEvent& mouseEvent,
     bool sendMouseEvent, bool setPointerPosition)
 {
-    RawPtr<PointerEvent> pointerEvent = prpPointerEvent;
-    RawPtr<EventTarget> hitTestTarget = prpHitTestTarget;
     bool isCaptureChanged = false;
 
     if (setPointerPosition) {
@@ -447,17 +429,15 @@
 }
 
 bool PointerEventManager::processPendingPointerCapture(
-    const RawPtr<PointerEvent> prpPointerEvent,
-    const RawPtr<EventTarget> prpHitTestTarget,
+    PointerEvent* pointerEvent,
+    EventTarget* hitTestTarget,
     const PlatformMouseEvent& mouseEvent, bool sendMouseEvent)
 {
-    RawPtr<PointerEvent> pointerEvent = prpPointerEvent;
-    RawPtr<EventTarget> hitTestTarget = prpHitTestTarget;
     int pointerId = pointerEvent->pointerId();
-    const RawPtr<EventTarget> pointerCaptureTarget =
+    EventTarget* pointerCaptureTarget =
         m_pointerCaptureTarget.contains(pointerId)
         ? m_pointerCaptureTarget.get(pointerId) : nullptr;
-    const RawPtr<EventTarget> pendingPointerCaptureTarget =
+    EventTarget* pendingPointerCaptureTarget =
         m_pendingPointerCaptureTarget.contains(pointerId)
         ? m_pendingPointerCaptureTarget.get(pointerId) : nullptr;
     const EventTargetAttributes &nodeUnderPointerAtt =
@@ -483,9 +463,9 @@
         if (pointerCaptureTarget) {
             // Re-target lostpointercapture to the document when the element is
             // no longer participating in the tree.
-            EventTarget* target = pointerCaptureTarget.get();
+            EventTarget* target = pointerCaptureTarget;
             if (target->toNode()
-                && !target->toNode()->inDocument()) {
+                && !target->toNode()->inShadowIncludingDocument()) {
                 target = target->toNode()->ownerDocument();
             }
             dispatchPointerEvent(target,
@@ -545,9 +525,8 @@
 }
 
 void PointerEventManager::removePointer(
-    const RawPtr<PointerEvent> prpPointerEvent)
+    PointerEvent* pointerEvent)
 {
-    RawPtr<PointerEvent> pointerEvent = prpPointerEvent;
     if (m_pointerEventFactory.remove(pointerEvent)) {
         int pointerId = pointerEvent->pointerId();
         m_pendingPointerCaptureTarget.remove(pointerId);
diff --git a/third_party/WebKit/Source/core/input/PointerEventManager.h b/third_party/WebKit/Source/core/input/PointerEventManager.h
index ef5e2af..42c08cc 100644
--- a/third_party/WebKit/Source/core/input/PointerEventManager.h
+++ b/third_party/WebKit/Source/core/input/PointerEventManager.h
@@ -26,20 +26,20 @@
     DECLARE_TRACE();
 
     WebInputEventResult sendMousePointerEvent(
-        RawPtr<Node>, const AtomicString& type,
+        Node*, const AtomicString& type,
         int clickCount, const PlatformMouseEvent&,
-        RawPtr<Node> relatedTarget,
-        RawPtr<AbstractView>,
-        RawPtr<Node> lastNodeUnderMouse);
+        Node* relatedTarget,
+        AbstractView*,
+        Node* lastNodeUnderMouse);
 
     // Returns whether the event is consumed or not
     WebInputEventResult sendTouchPointerEvent(
-        RawPtr<EventTarget>,
+        EventTarget*,
         const PlatformTouchPoint&, PlatformEvent::Modifiers,
         const double width, const double height,
         const double clientX, const double clientY);
 
-    void sendTouchCancelPointerEvent(RawPtr<EventTarget>,
+    void sendTouchCancelPointerEvent(EventTarget*,
         const PlatformTouchPoint&);
 
     // Sends node transition events mouseout/leave/over/enter to the
@@ -54,10 +54,10 @@
     // and their corresponding transition events will be handled altogether by
     // sendMousePointerEvent function.
     void sendMouseAndPossiblyPointerNodeTransitionEvents(
-        RawPtr<Node> exitedNode,
-        RawPtr<Node> enteredNode,
+        Node* exitedNode,
+        Node* enteredNode,
         const PlatformMouseEvent&,
-        RawPtr<AbstractView>, bool isFrameBoundaryTransition);
+        AbstractView*, bool isFrameBoundaryTransition);
 
     // Clear all the existing ids.
     void clear();
@@ -82,27 +82,27 @@
         EventTargetAttributes()
         : target(nullptr)
         , hasRecievedOverEvent(false) {}
-        EventTargetAttributes(RawPtr<EventTarget> target,
+        EventTargetAttributes(EventTarget* target,
             bool hasRecievedOverEvent)
         : target(target)
         , hasRecievedOverEvent(hasRecievedOverEvent) {}
     };
 
     void sendNodeTransitionEvents(
-        RawPtr<EventTarget> exitedTarget,
-        RawPtr<EventTarget> enteredTarget,
-        RawPtr<PointerEvent>,
+        EventTarget* exitedTarget,
+        EventTarget* enteredTarget,
+        PointerEvent*,
         const PlatformMouseEvent& = PlatformMouseEvent(),
         bool sendMouseEvent = false);
-    void setNodeUnderPointer(RawPtr<PointerEvent>,
-        RawPtr<EventTarget>, bool sendEvent = true);
+    void setNodeUnderPointer(PointerEvent*,
+        EventTarget*, bool sendEvent = true);
 
     // Returns whether the pointer capture is changed. In this case this
     // function will take care of transition events and setNodeUnderPointer
     // should not send transition events.
     bool processPendingPointerCapture(
-        const RawPtr<PointerEvent>,
-        const RawPtr<EventTarget>,
+        PointerEvent*,
+        EventTarget*,
         const PlatformMouseEvent& = PlatformMouseEvent(),
         bool sendMouseEvent = false);
 
@@ -111,22 +111,22 @@
     // setPointerPosition is true. It also sends corresponding transition events
     // for mouse if sendMouseEvent is true.
     void processCaptureAndPositionOfPointerEvent(
-        const RawPtr<PointerEvent>,
-        const RawPtr<EventTarget> hitTestTarget,
-        const RawPtr<EventTarget> lastNodeUnderMouse = nullptr,
+        PointerEvent*,
+        EventTarget* hitTestTarget,
+        EventTarget* lastNodeUnderMouse = nullptr,
         const PlatformMouseEvent& = PlatformMouseEvent(),
         bool sendMouseEvent = false,
         bool setPointerPosition = true);
 
     void removeTargetFromPointerCapturingMapping(
         PointerCapturingMap&, const EventTarget*);
-    RawPtr<EventTarget> getEffectiveTargetForPointerEvent(
-        RawPtr<EventTarget>, int);
+    EventTarget* getEffectiveTargetForPointerEvent(
+        EventTarget*, int);
     EventTarget* getCapturingNode(int);
-    void removePointer(const RawPtr<PointerEvent>);
+    void removePointer(PointerEvent*);
     WebInputEventResult dispatchPointerEvent(
-        RawPtr<EventTarget>,
-        RawPtr<PointerEvent>,
+        EventTarget*,
+        PointerEvent*,
         bool checkForListener = false);
     void releasePointerCapture(int);
 
diff --git a/third_party/WebKit/Source/core/inspector/InspectorDOMDebuggerAgent.cpp b/third_party/WebKit/Source/core/inspector/InspectorDOMDebuggerAgent.cpp
index 507fb3a..006d26d7 100644
--- a/third_party/WebKit/Source/core/inspector/InspectorDOMDebuggerAgent.cpp
+++ b/third_party/WebKit/Source/core/inspector/InspectorDOMDebuggerAgent.cpp
@@ -63,15 +63,6 @@
 
 namespace blink {
 
-static const char requestAnimationFrameEventName[] = "requestAnimationFrame";
-static const char cancelAnimationFrameEventName[] = "cancelAnimationFrame";
-static const char animationFrameFiredEventName[] = "animationFrameFired";
-static const char setInnerHTMLEventName[] = "setInnerHTML";
-static const char setTimerEventName[] = "setTimer";
-static const char clearTimerEventName[] = "clearTimer";
-static const char timerFiredEventName[] = "timerFired";
-static const char scriptFirstStatementEventName[] = "scriptFirstStatement";
-static const char windowCloseEventName[] = "close";
 static const char webglErrorFiredEventName[] = "webglErrorFired";
 static const char webglWarningFiredEventName[] = "webglWarningFired";
 static const char webglErrorNameProperty[] = "webglErrorName";
@@ -415,6 +406,11 @@
     return value.release();
 }
 
+void InspectorDOMDebuggerAgent::allowNativeBreakpoint(const String& breakpointName, bool sync)
+{
+    pauseOnNativeEventIfNeeded(preparePauseOnNativeEventData(breakpointName, 0), sync);
+}
+
 void InspectorDOMDebuggerAgent::willInsertDOMNode(Node* parent)
 {
     if (hasBreakpoint(parent, SubtreeModified)) {
@@ -448,11 +444,6 @@
     }
 }
 
-void InspectorDOMDebuggerAgent::willSetInnerHTML()
-{
-    pauseOnNativeEventIfNeeded(preparePauseOnNativeEventData(setInnerHTMLEventName, 0), true);
-}
-
 void InspectorDOMDebuggerAgent::descriptionForDOMEvent(Node* target, int breakpointType, bool insertion, protocol::DictionaryValue* description)
 {
     ASSERT(hasBreakpoint(target, breakpointType));
@@ -546,41 +537,6 @@
     return eventData.release();
 }
 
-void InspectorDOMDebuggerAgent::didInstallTimer(ExecutionContext*, int, int, bool)
-{
-    pauseOnNativeEventIfNeeded(preparePauseOnNativeEventData(setTimerEventName, 0), true);
-}
-
-void InspectorDOMDebuggerAgent::didRemoveTimer(ExecutionContext*, int)
-{
-    pauseOnNativeEventIfNeeded(preparePauseOnNativeEventData(clearTimerEventName, 0), true);
-}
-
-void InspectorDOMDebuggerAgent::willFireTimer(ExecutionContext*, int)
-{
-    pauseOnNativeEventIfNeeded(preparePauseOnNativeEventData(timerFiredEventName, 0), false);
-}
-
-void InspectorDOMDebuggerAgent::didFireTimer()
-{
-    m_debuggerAgent->cancelPauseOnNextStatement();
-}
-
-void InspectorDOMDebuggerAgent::didRequestAnimationFrame(ExecutionContext*, int)
-{
-    pauseOnNativeEventIfNeeded(preparePauseOnNativeEventData(requestAnimationFrameEventName, 0), true);
-}
-
-void InspectorDOMDebuggerAgent::didCancelAnimationFrame(ExecutionContext*, int)
-{
-    pauseOnNativeEventIfNeeded(preparePauseOnNativeEventData(cancelAnimationFrameEventName, 0), true);
-}
-
-void InspectorDOMDebuggerAgent::willFireAnimationFrame(ExecutionContext*, int)
-{
-    pauseOnNativeEventIfNeeded(preparePauseOnNativeEventData(animationFrameFiredEventName, 0), false);
-}
-
 void InspectorDOMDebuggerAgent::willHandleEvent(EventTarget* target, Event* event, EventListener*, bool)
 {
     Node* node = target->toNode();
@@ -588,21 +544,6 @@
     pauseOnNativeEventIfNeeded(preparePauseOnNativeEventData(event->type(), &targetName), false);
 }
 
-void InspectorDOMDebuggerAgent::didHandleEvent()
-{
-    m_debuggerAgent->cancelPauseOnNextStatement();
-}
-
-void InspectorDOMDebuggerAgent::willEvaluateScript()
-{
-    pauseOnNativeEventIfNeeded(preparePauseOnNativeEventData(scriptFirstStatementEventName, 0), false);
-}
-
-void InspectorDOMDebuggerAgent::willCloseWindow()
-{
-    pauseOnNativeEventIfNeeded(preparePauseOnNativeEventData(windowCloseEventName, 0), true);
-}
-
 void InspectorDOMDebuggerAgent::didFireWebGLError(const String& errorName)
 {
     OwnPtr<protocol::DictionaryValue> eventData = preparePauseOnNativeEventData(webglErrorFiredEventName, 0);
diff --git a/third_party/WebKit/Source/core/inspector/InspectorDOMDebuggerAgent.h b/third_party/WebKit/Source/core/inspector/InspectorDOMDebuggerAgent.h
index 45b8df6..1a9ef57b 100644
--- a/third_party/WebKit/Source/core/inspector/InspectorDOMDebuggerAgent.h
+++ b/third_party/WebKit/Source/core/inspector/InspectorDOMDebuggerAgent.h
@@ -78,28 +78,18 @@
     void getEventListeners(ErrorString*, const String16& objectId, OwnPtr<protocol::Array<protocol::DOMDebugger::EventListener>>* listeners) override;
 
     // InspectorInstrumentation API
+    void allowNativeBreakpoint(const String& breakpointName, bool sync);
     void willInsertDOMNode(Node* parent);
     void didInvalidateStyleAttr(Node*);
     void didInsertDOMNode(Node*);
     void willRemoveDOMNode(Node*);
     void didRemoveDOMNode(Node*);
     void willModifyDOMAttr(Element*, const AtomicString&, const AtomicString&);
-    void willSetInnerHTML();
     void willSendXMLHttpRequest(const String& url);
-    void didInstallTimer(ExecutionContext*, int timerId, int timeout, bool singleShot);
-    void didRemoveTimer(ExecutionContext*, int timerId);
-    void willFireTimer(ExecutionContext*, int timerId);
-    void didFireTimer();
-    void didRequestAnimationFrame(ExecutionContext*, int callbackId);
-    void didCancelAnimationFrame(ExecutionContext*, int callbackId);
-    void willFireAnimationFrame(ExecutionContext*, int callbackId);
     void willHandleEvent(EventTarget*, Event*, EventListener*, bool useCapture);
-    void didHandleEvent();
-    void willEvaluateScript();
     void didFireWebGLError(const String& errorName);
     void didFireWebGLWarning();
     void didFireWebGLErrorOrWarning(const String& message);
-    void willCloseWindow();
 
     void disable(ErrorString*) override;
     void restore() override;
diff --git a/third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.cpp b/third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.cpp
index 5eca1abd..25294e6 100644
--- a/third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.cpp
+++ b/third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.cpp
@@ -31,7 +31,7 @@
 
 #include "bindings/core/v8/V8Binding.h"
 #include "platform/ScriptForbiddenScope.h"
-#include "platform/v8_inspector/public/V8Debugger.h"
+#include "platform/v8_inspector/public/V8DebuggerAgent.h"
 
 namespace blink {
 
@@ -41,9 +41,9 @@
 static const char debuggerEnabled[] = "debuggerEnabled";
 }
 
-InspectorDebuggerAgent::InspectorDebuggerAgent(V8RuntimeAgent* runtimeAgent)
+InspectorDebuggerAgent::InspectorDebuggerAgent(V8DebuggerAgent* agent)
     : InspectorBaseAgent<InspectorDebuggerAgent, protocol::Frontend::Debugger>("Debugger")
-    , m_v8DebuggerAgent(V8DebuggerAgent::create(runtimeAgent))
+    , m_v8DebuggerAgent(agent)
 {
 }
 
@@ -334,9 +334,4 @@
     enable(&errorString);
 }
 
-void InspectorDebuggerAgent::discardAgent()
-{
-    m_v8DebuggerAgent.clear();
-}
-
 } // namespace blink
diff --git a/third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.h b/third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.h
index 11befd1..eb7d04f 100644
--- a/third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.h
+++ b/third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.h
@@ -32,10 +32,11 @@
 
 #include "core/CoreExport.h"
 #include "core/inspector/InspectorBaseAgent.h"
-#include "platform/v8_inspector/public/V8DebuggerAgent.h"
 
 namespace blink {
 
+class V8DebuggerAgent;
+
 using protocol::Array;
 
 class CORE_EXPORT InspectorDebuggerAgent
@@ -93,14 +94,13 @@
     void setFrontend(protocol::Frontend*) override;
     void clearFrontend() override;
     void restore() override;
-    void discardAgent() override;
 
-    V8DebuggerAgent* v8Agent() const { return m_v8DebuggerAgent.get(); }
+    V8DebuggerAgent* v8Agent() const { return m_v8DebuggerAgent; }
 
 protected:
-    explicit InspectorDebuggerAgent(V8RuntimeAgent*);
+    explicit InspectorDebuggerAgent(V8DebuggerAgent*);
 
-    OwnPtr<V8DebuggerAgent> m_v8DebuggerAgent;
+    V8DebuggerAgent* m_v8DebuggerAgent;
 };
 
 } // namespace blink
diff --git a/third_party/WebKit/Source/core/inspector/InspectorHeapProfilerAgent.cpp b/third_party/WebKit/Source/core/inspector/InspectorHeapProfilerAgent.cpp
index 46e47da5..1c1d178e 100644
--- a/third_party/WebKit/Source/core/inspector/InspectorHeapProfilerAgent.cpp
+++ b/third_party/WebKit/Source/core/inspector/InspectorHeapProfilerAgent.cpp
@@ -72,14 +72,14 @@
     m_timer.startRepeating(0.05, BLINK_FROM_HERE);
 }
 
-RawPtr<InspectorHeapProfilerAgent> InspectorHeapProfilerAgent::create(v8::Isolate* isolate, V8RuntimeAgent* runtimeAgent)
+RawPtr<InspectorHeapProfilerAgent> InspectorHeapProfilerAgent::create(v8::Isolate* isolate, V8HeapProfilerAgent* agent)
 {
-    return new InspectorHeapProfilerAgent(isolate, runtimeAgent);
+    return new InspectorHeapProfilerAgent(isolate, agent);
 }
 
-InspectorHeapProfilerAgent::InspectorHeapProfilerAgent(v8::Isolate* isolate, V8RuntimeAgent* runtimeAgent)
+InspectorHeapProfilerAgent::InspectorHeapProfilerAgent(v8::Isolate* isolate, V8HeapProfilerAgent* agent)
     : InspectorBaseAgent<InspectorHeapProfilerAgent, protocol::Frontend::HeapProfiler>("HeapProfiler")
-    , m_v8HeapProfilerAgent(V8HeapProfilerAgent::create(isolate, runtimeAgent))
+    , m_v8HeapProfilerAgent(agent)
     , m_isolate(isolate)
 {
 }
@@ -114,11 +114,6 @@
         startUpdateStatsTimer();
 }
 
-void InspectorHeapProfilerAgent::discardAgent()
-{
-    m_v8HeapProfilerAgent.clear();
-}
-
 // Protocol implementation.
 void InspectorHeapProfilerAgent::collectGarbage(ErrorString* error)
 {
@@ -141,7 +136,7 @@
 {
     if (m_heapStatsUpdateTask)
         return;
-    m_heapStatsUpdateTask = adoptPtr(new HeapStatsUpdateTask(m_v8HeapProfilerAgent.get()));
+    m_heapStatsUpdateTask = adoptPtr(new HeapStatsUpdateTask(m_v8HeapProfilerAgent));
     m_heapStatsUpdateTask->startTimer();
 }
 
diff --git a/third_party/WebKit/Source/core/inspector/InspectorHeapProfilerAgent.h b/third_party/WebKit/Source/core/inspector/InspectorHeapProfilerAgent.h
index fff4d023..6c55382 100644
--- a/third_party/WebKit/Source/core/inspector/InspectorHeapProfilerAgent.h
+++ b/third_party/WebKit/Source/core/inspector/InspectorHeapProfilerAgent.h
@@ -45,12 +45,11 @@
 namespace blink {
 
 class V8HeapProfilerAgent;
-class V8RuntimeAgent;
 
 class CORE_EXPORT InspectorHeapProfilerAgent final : public InspectorBaseAgent<InspectorHeapProfilerAgent, protocol::Frontend::HeapProfiler>, public protocol::Backend::HeapProfiler {
     WTF_MAKE_NONCOPYABLE(InspectorHeapProfilerAgent);
 public:
-    static RawPtr<InspectorHeapProfilerAgent> create(v8::Isolate*, V8RuntimeAgent*);
+    static RawPtr<InspectorHeapProfilerAgent> create(v8::Isolate*, V8HeapProfilerAgent*);
     ~InspectorHeapProfilerAgent() override;
 
     // InspectorBaseAgent overrides.
@@ -58,7 +57,6 @@
     void setFrontend(protocol::Frontend*) override;
     void clearFrontend() override;
     void restore() override;
-    void discardAgent() override;
 
     void enable(ErrorString*) override;
     void disable(ErrorString*) override;
@@ -75,13 +73,13 @@
 private:
     class HeapStatsUpdateTask;
 
-    InspectorHeapProfilerAgent(v8::Isolate*, V8RuntimeAgent*);
+    InspectorHeapProfilerAgent(v8::Isolate*, V8HeapProfilerAgent*);
 
     void startUpdateStatsTimer();
     void stopUpdateStatsTimer();
     bool isInspectableHeapObject(int id);
 
-    OwnPtr<V8HeapProfilerAgent> m_v8HeapProfilerAgent;
+    V8HeapProfilerAgent* m_v8HeapProfilerAgent;
     OwnPtr<HeapStatsUpdateTask> m_heapStatsUpdateTask;
     v8::Isolate* m_isolate;
 };
diff --git a/third_party/WebKit/Source/core/inspector/InspectorInstrumentation.idl b/third_party/WebKit/Source/core/inspector/InspectorInstrumentation.idl
index 364ff39..b5b9eb69 100644
--- a/third_party/WebKit/Source/core/inspector/InspectorInstrumentation.idl
+++ b/third_party/WebKit/Source/core/inspector/InspectorInstrumentation.idl
@@ -72,9 +72,6 @@
     void didClearDocumentOfWindowObject([Keep] LocalFrame*);
 
     [DOMDebugger, Inline=FastReturn]
-    void willCloseWindow(ExecutionContext*);
-
-    [DOMDebugger, Inline=FastReturn]
     void willInsertDOMNode([Keep] Node* parent);
 
     [DOM, DOMDebugger, Inline=FastReturn]
@@ -116,9 +113,6 @@
     [DOM, Inline=FastReturn]
     void willPopShadowRoot([Keep] Element* host, ShadowRoot*);
 
-    [DOMDebugger]
-    void willSetInnerHTML(Element* element);
-
     [DOMDebugger, Inline=FastReturn]
     void willSendXMLHttpRequest(ExecutionContext*, const String& url);
 
@@ -131,12 +125,6 @@
     [DOMDebugger, Inline=FastReturn]
     void didFireWebGLErrorOrWarning(Element*, const String& message);
 
-    [DOMDebugger, Inline=FastReturn]
-    void didInstallTimer([Keep] ExecutionContext*, int timerId, int timeout, bool singleShot);
-
-    [DOMDebugger, Inline=FastReturn]
-    void didRemoveTimer([Keep] ExecutionContext*, int timerId);
-
     [Debugger, Inline=FastReturn]
     InspectorInstrumentationCookie willExecuteScript(ExecutionContext*, int scriptId);
 
@@ -144,19 +132,7 @@
     void didExecuteScript(const InspectorInstrumentationCookie&);
 
     [DOMDebugger, Inline=FastReturn]
-    InspectorInstrumentationCookie willHandleEvent([Keep] EventTarget*, Event*, EventListener* listener, bool useCapture);
-
-    [DOMDebugger, Inline=FastReturn]
-    void didHandleEvent(const InspectorInstrumentationCookie&);
-
-    [DOMDebugger, Inline=FastReturn]
-    void willEvaluateScript(ExecutionContext*);
-
-    [DOMDebugger, Inline=FastReturn]
-    InspectorInstrumentationCookie willFireTimer([Keep] ExecutionContext*, int timerId);
-
-    [DOMDebugger, Inline=FastReturn]
-    void didFireTimer(const InspectorInstrumentationCookie&);
+    void willHandleEvent([Keep] EventTarget*, Event*, EventListener* listener, bool useCapture);
 
     [Page, Inline=FastReturn]
     void didUpdateLayout(LocalFrame*);
@@ -290,15 +266,9 @@
     [Inline=Forward]
     void removedResourceFromMemoryCache(Resource* cachedResource);
 
-    [DOMDebugger] 
-    void didRequestAnimationFrame([Keep] ExecutionContext*, int callbackId);   
-   
-    [DOMDebugger]    
-    void didCancelAnimationFrame([Keep] ExecutionContext*, int callbackId);    
-   
-    [DOMDebugger]    
-    void willFireAnimationFrame([Keep] ExecutionContext*, int callbackId);   
-    
+    [DOMDebugger]
+    void allowNativeBreakpoint(ExecutionContext*, const String& name, bool sync);
+
     [Worker]
     void didStartWorker(ExecutionContext*, WorkerInspectorProxy* proxy, bool waitingForDebugger);
 
diff --git a/third_party/WebKit/Source/core/inspector/InspectorPageAgent.cpp b/third_party/WebKit/Source/core/inspector/InspectorPageAgent.cpp
index 0e42b39..836cdc8 100644
--- a/third_party/WebKit/Source/core/inspector/InspectorPageAgent.cpp
+++ b/third_party/WebKit/Source/core/inspector/InspectorPageAgent.cpp
@@ -64,6 +64,7 @@
 #include "platform/UserGestureIndicator.h"
 #include "platform/inspector_protocol/Values.h"
 #include "platform/v8_inspector/public/V8ContentSearchUtil.h"
+#include "platform/v8_inspector/public/V8DebuggerAgent.h"
 #include "platform/weborigin/SecurityOrigin.h"
 #include "wtf/CurrentTime.h"
 #include "wtf/ListHashSet.h"
diff --git a/third_party/WebKit/Source/core/inspector/InspectorProfilerAgent.cpp b/third_party/WebKit/Source/core/inspector/InspectorProfilerAgent.cpp
index d6bf196..62933e5 100644
--- a/third_party/WebKit/Source/core/inspector/InspectorProfilerAgent.cpp
+++ b/third_party/WebKit/Source/core/inspector/InspectorProfilerAgent.cpp
@@ -41,15 +41,15 @@
 static const char profilerEnabled[] = "profilerEnabled";
 }
 
-RawPtr<InspectorProfilerAgent> InspectorProfilerAgent::create(V8Debugger* debugger, Client* client)
+RawPtr<InspectorProfilerAgent> InspectorProfilerAgent::create(V8ProfilerAgent* agent, Client* client)
 {
-    return new InspectorProfilerAgent(debugger, client);
+    return new InspectorProfilerAgent(agent, client);
 }
 
-InspectorProfilerAgent::InspectorProfilerAgent(V8Debugger* debugger, Client* client)
+InspectorProfilerAgent::InspectorProfilerAgent(V8ProfilerAgent* agent, Client* client)
     : InspectorBaseAgent<InspectorProfilerAgent, protocol::Frontend::Profiler>("Profiler")
     , m_client(client)
-    , m_v8ProfilerAgent(V8ProfilerAgent::create(debugger))
+    , m_v8ProfilerAgent(agent)
 {
 }
 
@@ -85,11 +85,6 @@
     enable(&errorString);
 }
 
-void InspectorProfilerAgent::discardAgent()
-{
-    m_v8ProfilerAgent.clear();
-}
-
 // Protocol implementation.
 void InspectorProfilerAgent::consoleProfile(ExecutionContext* context, const String16& title)
 {
diff --git a/third_party/WebKit/Source/core/inspector/InspectorProfilerAgent.h b/third_party/WebKit/Source/core/inspector/InspectorProfilerAgent.h
index f311813c..f4b5cf8 100644
--- a/third_party/WebKit/Source/core/inspector/InspectorProfilerAgent.h
+++ b/third_party/WebKit/Source/core/inspector/InspectorProfilerAgent.h
@@ -41,7 +41,6 @@
 
 class ExecutionContext;
 class InspectorFrontend;
-class V8Debugger;
 class V8ProfilerAgent;
 
 class CORE_EXPORT InspectorProfilerAgent final : public InspectorBaseAgent<InspectorProfilerAgent, protocol::Frontend::Profiler>, public protocol::Backend::Profiler {
@@ -54,7 +53,7 @@
         virtual void profilingStopped() { }
     };
 
-    static RawPtr<InspectorProfilerAgent> create(V8Debugger*, Client*);
+    static RawPtr<InspectorProfilerAgent> create(V8ProfilerAgent*, Client*);
     ~InspectorProfilerAgent() override;
     DECLARE_VIRTUAL_TRACE();
 
@@ -63,7 +62,6 @@
     void setFrontend(protocol::Frontend*) override;
     void clearFrontend() override;
     void restore() override;
-    void discardAgent() override;
 
     void consoleProfile(ExecutionContext*, const String16& title);
     void consoleProfileEnd(const String16& title);
@@ -80,10 +78,10 @@
     void didLeaveNestedRunLoop();
 
 private:
-    InspectorProfilerAgent(V8Debugger*, Client*);
+    InspectorProfilerAgent(V8ProfilerAgent*, Client*);
 
     Client* m_client;
-    OwnPtr<V8ProfilerAgent> m_v8ProfilerAgent;
+    V8ProfilerAgent* m_v8ProfilerAgent;
 };
 
 } // namespace blink
diff --git a/third_party/WebKit/Source/core/inspector/InspectorResourceAgent.cpp b/third_party/WebKit/Source/core/inspector/InspectorResourceAgent.cpp
index aead12f..2d13d34 100644
--- a/third_party/WebKit/Source/core/inspector/InspectorResourceAgent.cpp
+++ b/third_party/WebKit/Source/core/inspector/InspectorResourceAgent.cpp
@@ -757,14 +757,22 @@
 
 void InspectorResourceAgent::removedResourceFromMemoryCache(Resource* cachedResource)
 {
-    String content;
-    bool base64Encoded;
-    bool hasContent = InspectorPageAgent::cachedResourceContent(cachedResource, &content, &base64Encoded);
-    Vector<String> requestIds = m_resourcesData->removeResource(cachedResource);
-    if (hasContent && !isErrorStatusCode(cachedResource->response().httpStatusCode())) {
-        for (auto& request : requestIds)
-            m_resourcesData->setResourceContent(request, content, base64Encoded);
+    // Mark loaded resources or resources without the buffer as loaded.
+    if (cachedResource->isLoaded() || !cachedResource->resourceBuffer()) {
+        String content;
+        bool base64Encoded;
+        bool hasContent = InspectorPageAgent::cachedResourceContent(cachedResource, &content, &base64Encoded);
+        Vector<String> requestIds = m_resourcesData->removeResource(cachedResource);
+        if (hasContent && !isErrorStatusCode(cachedResource->response().httpStatusCode())) {
+            for (auto& request : requestIds)
+                m_resourcesData->setResourceContent(request, content, base64Encoded);
+        }
+        return;
     }
+    // We could be evicting resource being loaded, save the loaded part, the rest will be appended.
+    Vector<String> requestIds = m_resourcesData->removeResource(cachedResource);
+    for (auto& request : requestIds)
+        m_resourcesData->maybeAddResourceData(request, cachedResource->resourceBuffer()->data(), cachedResource->resourceBuffer()->size());
 }
 
 void InspectorResourceAgent::applyUserAgentOverride(String* userAgent)
diff --git a/third_party/WebKit/Source/core/inspector/InspectorRuntimeAgent.cpp b/third_party/WebKit/Source/core/inspector/InspectorRuntimeAgent.cpp
index f6f742a1..961cdc3 100644
--- a/third_party/WebKit/Source/core/inspector/InspectorRuntimeAgent.cpp
+++ b/third_party/WebKit/Source/core/inspector/InspectorRuntimeAgent.cpp
@@ -44,10 +44,10 @@
 static const char runtimeEnabled[] = "runtimeEnabled";
 };
 
-InspectorRuntimeAgent::InspectorRuntimeAgent(V8Debugger* debugger, Client* client, int contextGroupId)
+InspectorRuntimeAgent::InspectorRuntimeAgent(V8RuntimeAgent* agent, Client* client)
     : InspectorBaseAgent<InspectorRuntimeAgent, protocol::Frontend::Runtime>("Runtime")
     , m_enabled(false)
-    , m_v8RuntimeAgent(V8RuntimeAgent::create(debugger, contextGroupId))
+    , m_v8RuntimeAgent(agent)
     , m_client(client)
 {
 }
@@ -84,11 +84,6 @@
     enable(&errorString);
 }
 
-void InspectorRuntimeAgent::discardAgent()
-{
-    m_v8RuntimeAgent.clear();
-}
-
 void InspectorRuntimeAgent::evaluate(ErrorString* errorString,
     const String16& expression,
     const Maybe<String16>& objectGroup,
diff --git a/third_party/WebKit/Source/core/inspector/InspectorRuntimeAgent.h b/third_party/WebKit/Source/core/inspector/InspectorRuntimeAgent.h
index 35143493..61e6f4f 100644
--- a/third_party/WebKit/Source/core/inspector/InspectorRuntimeAgent.h
+++ b/third_party/WebKit/Source/core/inspector/InspectorRuntimeAgent.h
@@ -33,7 +33,6 @@
 
 #include "core/CoreExport.h"
 #include "core/inspector/InspectorBaseAgent.h"
-#include "platform/v8_inspector/public/V8RuntimeAgent.h"
 #include "wtf/Forward.h"
 #include "wtf/Noncopyable.h"
 
@@ -42,7 +41,7 @@
 class InjectedScript;
 class InjectedScriptManager;
 class ScriptState;
-class V8Debugger;
+class V8RuntimeAgent;
 
 namespace protocol {
 class ListValue;
@@ -69,7 +68,6 @@
     void setFrontend(protocol::Frontend*) override;
     void clearFrontend() override;
     void restore() override;
-    void discardAgent() override;
 
     // Part of the protocol.
     void evaluate(ErrorString*, const String16& expression, const Maybe<String16>& objectGroup, const Maybe<bool>& includeCommandLineAPI, const Maybe<bool>& doNotPauseOnExceptionsAndMuteConsole, const Maybe<int>& contextId, const Maybe<bool>& returnByValue, const Maybe<bool>& generatePreview, const Maybe<bool>& userGesture, OwnPtr<protocol::Runtime::RemoteObject>* result, Maybe<bool>* wasThrown, Maybe<protocol::Runtime::ExceptionDetails>*) override;
@@ -84,13 +82,11 @@
     void compileScript(ErrorString*, const String16& expression, const String16& sourceURL, bool persistScript, int executionContextId, Maybe<String16>* scriptId, Maybe<protocol::Runtime::ExceptionDetails>*) override;
     void runScript(ErrorString*, const String16& scriptId, int executionContextId, const Maybe<String16>& objectGroup, const Maybe<bool>& doNotPauseOnExceptionsAndMuteConsole, const Maybe<bool>& includeCommandLineAPI, OwnPtr<protocol::Runtime::RemoteObject>* result, Maybe<protocol::Runtime::ExceptionDetails>*) override;
 
-    V8RuntimeAgent* v8Agent() { return m_v8RuntimeAgent.get(); }
-
 protected:
-    InspectorRuntimeAgent(V8Debugger*, Client*, int contextGroupId);
+    InspectorRuntimeAgent(V8RuntimeAgent*, Client*);
 
     bool m_enabled;
-    OwnPtr<V8RuntimeAgent> m_v8RuntimeAgent;
+    V8RuntimeAgent* m_v8RuntimeAgent;
     Client* m_client;
 };
 
diff --git a/third_party/WebKit/Source/core/inspector/PageDebuggerAgent.cpp b/third_party/WebKit/Source/core/inspector/PageDebuggerAgent.cpp
index b30bdf1..22fedcb 100644
--- a/third_party/WebKit/Source/core/inspector/PageDebuggerAgent.cpp
+++ b/third_party/WebKit/Source/core/inspector/PageDebuggerAgent.cpp
@@ -46,13 +46,13 @@
 
 namespace blink {
 
-RawPtr<PageDebuggerAgent> PageDebuggerAgent::create(InspectedFrames* inspectedFrames, V8RuntimeAgent* runtimeAgent)
+RawPtr<PageDebuggerAgent> PageDebuggerAgent::create(V8DebuggerAgent* agent, InspectedFrames* inspectedFrames)
 {
-    return new PageDebuggerAgent(inspectedFrames, runtimeAgent);
+    return new PageDebuggerAgent(agent, inspectedFrames);
 }
 
-PageDebuggerAgent::PageDebuggerAgent(InspectedFrames* inspectedFrames, V8RuntimeAgent* runtimeAgent)
-    : InspectorDebuggerAgent(runtimeAgent)
+PageDebuggerAgent::PageDebuggerAgent(V8DebuggerAgent* agent, InspectedFrames* inspectedFrames)
+    : InspectorDebuggerAgent(agent)
     , m_inspectedFrames(inspectedFrames)
 {
 }
diff --git a/third_party/WebKit/Source/core/inspector/PageDebuggerAgent.h b/third_party/WebKit/Source/core/inspector/PageDebuggerAgent.h
index 5212d40a..dfd8cab 100644
--- a/third_party/WebKit/Source/core/inspector/PageDebuggerAgent.h
+++ b/third_party/WebKit/Source/core/inspector/PageDebuggerAgent.h
@@ -47,7 +47,7 @@
     : public InspectorDebuggerAgent {
     WTF_MAKE_NONCOPYABLE(PageDebuggerAgent);
 public:
-    static RawPtr<PageDebuggerAgent> create(InspectedFrames*, V8RuntimeAgent*);
+    static RawPtr<PageDebuggerAgent> create(V8DebuggerAgent*, InspectedFrames*);
     ~PageDebuggerAgent() override;
     DECLARE_VIRTUAL_TRACE();
 
@@ -58,7 +58,7 @@
     void didStartProvisionalLoad(LocalFrame*);
 
 private:
-    PageDebuggerAgent(InspectedFrames*, V8RuntimeAgent*);
+    PageDebuggerAgent(V8DebuggerAgent*, InspectedFrames*);
 
     // V8DebuggerAgent::Client implemntation.
     bool canExecuteScripts() const;
diff --git a/third_party/WebKit/Source/core/inspector/PageRuntimeAgent.cpp b/third_party/WebKit/Source/core/inspector/PageRuntimeAgent.cpp
index 05fddc6..b10b2e6 100644
--- a/third_party/WebKit/Source/core/inspector/PageRuntimeAgent.cpp
+++ b/third_party/WebKit/Source/core/inspector/PageRuntimeAgent.cpp
@@ -38,15 +38,14 @@
 #include "core/inspector/InspectedFrames.h"
 #include "core/inspector/InstrumentingAgents.h"
 #include "core/page/Page.h"
-#include "platform/v8_inspector/public/V8RuntimeAgent.h"
 #include "platform/weborigin/SecurityOrigin.h"
 
 using blink::protocol::Runtime::ExceptionDetails;
 
 namespace blink {
 
-PageRuntimeAgent::PageRuntimeAgent(Client* client, V8Debugger* debugger, InspectedFrames* inspectedFrames, int contextGroupId)
-    : InspectorRuntimeAgent(debugger, client, contextGroupId)
+PageRuntimeAgent::PageRuntimeAgent(Client* client, V8RuntimeAgent* agent, InspectedFrames* inspectedFrames)
+    : InspectorRuntimeAgent(agent, client)
     , m_inspectedFrames(inspectedFrames)
 {
 }
diff --git a/third_party/WebKit/Source/core/inspector/PageRuntimeAgent.h b/third_party/WebKit/Source/core/inspector/PageRuntimeAgent.h
index a754722..a389143 100644
--- a/third_party/WebKit/Source/core/inspector/PageRuntimeAgent.h
+++ b/third_party/WebKit/Source/core/inspector/PageRuntimeAgent.h
@@ -42,9 +42,9 @@
 
 class CORE_EXPORT PageRuntimeAgent final : public InspectorRuntimeAgent {
 public:
-    static RawPtr<PageRuntimeAgent> create(InspectorRuntimeAgent::Client* client, V8Debugger* debugger, InspectedFrames* inspectedFrames, int contextGroupId)
+    static RawPtr<PageRuntimeAgent> create(InspectorRuntimeAgent::Client* client, V8RuntimeAgent* agent, InspectedFrames* inspectedFrames)
     {
-        return new PageRuntimeAgent(client, debugger, inspectedFrames, contextGroupId);
+        return new PageRuntimeAgent(client, agent, inspectedFrames);
     }
     ~PageRuntimeAgent() override;
     DECLARE_VIRTUAL_TRACE();
@@ -52,7 +52,7 @@
     void disable(ErrorString*) override;
 
 private:
-    PageRuntimeAgent(Client*, V8Debugger*, InspectedFrames*, int contextGroupId);
+    PageRuntimeAgent(Client*, V8RuntimeAgent*, InspectedFrames*);
 
     Member<InspectedFrames> m_inspectedFrames;
 };
diff --git a/third_party/WebKit/Source/core/inspector/WorkerDebuggerAgent.cpp b/third_party/WebKit/Source/core/inspector/WorkerDebuggerAgent.cpp
index 56a0056..216a98e 100644
--- a/third_party/WebKit/Source/core/inspector/WorkerDebuggerAgent.cpp
+++ b/third_party/WebKit/Source/core/inspector/WorkerDebuggerAgent.cpp
@@ -34,13 +34,13 @@
 
 namespace blink {
 
-RawPtr<WorkerDebuggerAgent> WorkerDebuggerAgent::create(WorkerGlobalScope* inspectedWorkerGlobalScope, V8RuntimeAgent* runtimeAgent)
+RawPtr<WorkerDebuggerAgent> WorkerDebuggerAgent::create(V8DebuggerAgent* agent, WorkerGlobalScope* inspectedWorkerGlobalScope)
 {
-    return new WorkerDebuggerAgent(inspectedWorkerGlobalScope, runtimeAgent);
+    return new WorkerDebuggerAgent(agent, inspectedWorkerGlobalScope);
 }
 
-WorkerDebuggerAgent::WorkerDebuggerAgent(WorkerGlobalScope* inspectedWorkerGlobalScope, V8RuntimeAgent* runtimeAgent)
-    : InspectorDebuggerAgent(runtimeAgent)
+WorkerDebuggerAgent::WorkerDebuggerAgent(V8DebuggerAgent* agent, WorkerGlobalScope* inspectedWorkerGlobalScope)
+    : InspectorDebuggerAgent(agent)
     , m_inspectedWorkerGlobalScope(inspectedWorkerGlobalScope)
 {
 }
diff --git a/third_party/WebKit/Source/core/inspector/WorkerDebuggerAgent.h b/third_party/WebKit/Source/core/inspector/WorkerDebuggerAgent.h
index 256aa40..f3fad51 100644
--- a/third_party/WebKit/Source/core/inspector/WorkerDebuggerAgent.h
+++ b/third_party/WebKit/Source/core/inspector/WorkerDebuggerAgent.h
@@ -40,12 +40,12 @@
 class WorkerDebuggerAgent final : public InspectorDebuggerAgent {
     WTF_MAKE_NONCOPYABLE(WorkerDebuggerAgent);
 public:
-    static RawPtr<WorkerDebuggerAgent> create(WorkerGlobalScope*, V8RuntimeAgent*);
+    static RawPtr<WorkerDebuggerAgent> create(V8DebuggerAgent*, WorkerGlobalScope*);
     ~WorkerDebuggerAgent() override;
     DECLARE_VIRTUAL_TRACE();
 
 private:
-    WorkerDebuggerAgent(WorkerGlobalScope*, V8RuntimeAgent*);
+    WorkerDebuggerAgent(V8DebuggerAgent*, WorkerGlobalScope*);
 
     Member<WorkerGlobalScope> m_inspectedWorkerGlobalScope;
 };
diff --git a/third_party/WebKit/Source/core/inspector/WorkerInspectorController.cpp b/third_party/WebKit/Source/core/inspector/WorkerInspectorController.cpp
index 234ad6c..43da88b 100644
--- a/third_party/WebKit/Source/core/inspector/WorkerInspectorController.cpp
+++ b/third_party/WebKit/Source/core/inspector/WorkerInspectorController.cpp
@@ -45,6 +45,8 @@
 #include "core/workers/WorkerThread.h"
 #include "platform/inspector_protocol/Dispatcher.h"
 #include "platform/inspector_protocol/Frontend.h"
+#include "platform/v8_inspector/public/V8Debugger.h"
+#include "platform/v8_inspector/public/V8InspectorSession.h"
 #include "platform/v8_inspector/public/V8RuntimeAgent.h"
 #include "wtf/PassOwnPtr.h"
 
@@ -53,30 +55,34 @@
 RawPtr<WorkerInspectorController> WorkerInspectorController::create(WorkerGlobalScope* workerGlobalScope)
 {
     WorkerThreadDebugger* debugger = WorkerThreadDebugger::from(workerGlobalScope->thread()->isolate());
-    return debugger ? new WorkerInspectorController(workerGlobalScope, debugger->debugger(), debugger->contextGroupId()) : nullptr;
+    if (!debugger)
+        return nullptr;
+    OwnPtr<V8InspectorSession> session = debugger->debugger()->connect(debugger->contextGroupId());
+    return new WorkerInspectorController(workerGlobalScope, session.release());
 }
 
-WorkerInspectorController::WorkerInspectorController(WorkerGlobalScope* workerGlobalScope, V8Debugger* debugger, int contextGroupId)
+WorkerInspectorController::WorkerInspectorController(WorkerGlobalScope* workerGlobalScope, PassOwnPtr<V8InspectorSession> session)
     : m_workerGlobalScope(workerGlobalScope)
     , m_instrumentingAgents(InstrumentingAgents::create())
     , m_agents(m_instrumentingAgents.get())
+    , m_v8Session(session)
 {
-    RawPtr<WorkerRuntimeAgent> workerRuntimeAgent = WorkerRuntimeAgent::create(debugger, workerGlobalScope, this, contextGroupId);
+    RawPtr<WorkerRuntimeAgent> workerRuntimeAgent = WorkerRuntimeAgent::create(m_v8Session->runtimeAgent(), workerGlobalScope, this);
     m_workerRuntimeAgent = workerRuntimeAgent.get();
     m_agents.append(workerRuntimeAgent.release());
 
-    RawPtr<WorkerDebuggerAgent> workerDebuggerAgent = WorkerDebuggerAgent::create(workerGlobalScope, m_workerRuntimeAgent->v8Agent());
+    RawPtr<WorkerDebuggerAgent> workerDebuggerAgent = WorkerDebuggerAgent::create(m_v8Session->debuggerAgent(), workerGlobalScope);
     m_workerDebuggerAgent = workerDebuggerAgent.get();
     m_agents.append(workerDebuggerAgent.release());
 
-    m_agents.append(InspectorProfilerAgent::create(debugger, 0));
-    m_agents.append(InspectorHeapProfilerAgent::create(workerGlobalScope->thread()->isolate(), m_workerRuntimeAgent->v8Agent()));
+    m_agents.append(InspectorProfilerAgent::create(m_v8Session->profilerAgent(), nullptr));
+    m_agents.append(InspectorHeapProfilerAgent::create(workerGlobalScope->thread()->isolate(), m_v8Session->heapProfilerAgent()));
 
-    RawPtr<WorkerConsoleAgent> workerConsoleAgent = WorkerConsoleAgent::create(m_workerRuntimeAgent->v8Agent(), m_workerDebuggerAgent->v8Agent(), workerGlobalScope);
+    RawPtr<WorkerConsoleAgent> workerConsoleAgent = WorkerConsoleAgent::create(m_v8Session->runtimeAgent(), m_v8Session->debuggerAgent(), workerGlobalScope);
     WorkerConsoleAgent* workerConsoleAgentPtr = workerConsoleAgent.get();
     m_agents.append(workerConsoleAgent.release());
 
-    m_workerRuntimeAgent->v8Agent()->setClearConsoleCallback(bind<>(&InspectorConsoleAgent::clearAllMessages, workerConsoleAgentPtr));
+    m_v8Session->runtimeAgent()->setClearConsoleCallback(bind<>(&InspectorConsoleAgent::clearAllMessages, workerConsoleAgentPtr));
 }
 
 WorkerInspectorController::~WorkerInspectorController()
@@ -117,6 +123,7 @@
     disconnectFrontend();
     m_instrumentingAgents->reset();
     m_agents.discardAgents();
+    m_v8Session.clear();
 }
 
 void WorkerInspectorController::resumeStartup()
diff --git a/third_party/WebKit/Source/core/inspector/WorkerInspectorController.h b/third_party/WebKit/Source/core/inspector/WorkerInspectorController.h
index 00a0a14d..1a9e0814 100644
--- a/third_party/WebKit/Source/core/inspector/WorkerInspectorController.h
+++ b/third_party/WebKit/Source/core/inspector/WorkerInspectorController.h
@@ -45,6 +45,7 @@
 
 class InstrumentingAgents;
 class V8Debugger;
+class V8InspectorSession;
 class WorkerDebuggerAgent;
 class WorkerGlobalScope;
 class WorkerRuntimeAgent;
@@ -68,7 +69,7 @@
     void dispose();
 
 private:
-    WorkerInspectorController(WorkerGlobalScope*, V8Debugger*, int contextGroupId);
+    WorkerInspectorController(WorkerGlobalScope*, PassOwnPtr<V8InspectorSession>);
     friend InstrumentingAgents* instrumentationForWorkerGlobalScope(WorkerGlobalScope*);
 
     // InspectorRuntimeAgent::Client implementation.
@@ -82,6 +83,7 @@
     Member<WorkerGlobalScope> m_workerGlobalScope;
     Member<InstrumentingAgents> m_instrumentingAgents;
     InspectorAgentRegistry m_agents;
+    OwnPtr<V8InspectorSession> m_v8Session;
     OwnPtr<protocol::Frontend> m_frontend;
     OwnPtr<protocol::Dispatcher> m_backendDispatcher;
     Member<WorkerDebuggerAgent> m_workerDebuggerAgent;
diff --git a/third_party/WebKit/Source/core/inspector/WorkerRuntimeAgent.cpp b/third_party/WebKit/Source/core/inspector/WorkerRuntimeAgent.cpp
index 4004dd9..0fd3243e 100644
--- a/third_party/WebKit/Source/core/inspector/WorkerRuntimeAgent.cpp
+++ b/third_party/WebKit/Source/core/inspector/WorkerRuntimeAgent.cpp
@@ -35,8 +35,8 @@
 
 namespace blink {
 
-WorkerRuntimeAgent::WorkerRuntimeAgent(V8Debugger* debugger, WorkerGlobalScope* workerGlobalScope, InspectorRuntimeAgent::Client* client, int contextGroupId)
-    : InspectorRuntimeAgent(debugger, client, contextGroupId)
+WorkerRuntimeAgent::WorkerRuntimeAgent(V8RuntimeAgent* agent, WorkerGlobalScope* workerGlobalScope, InspectorRuntimeAgent::Client* client)
+    : InspectorRuntimeAgent(agent, client)
     , m_workerGlobalScope(workerGlobalScope)
 {
 }
diff --git a/third_party/WebKit/Source/core/inspector/WorkerRuntimeAgent.h b/third_party/WebKit/Source/core/inspector/WorkerRuntimeAgent.h
index dd0d22a..e8b5d27 100644
--- a/third_party/WebKit/Source/core/inspector/WorkerRuntimeAgent.h
+++ b/third_party/WebKit/Source/core/inspector/WorkerRuntimeAgent.h
@@ -40,9 +40,9 @@
 
 class WorkerRuntimeAgent final : public InspectorRuntimeAgent {
 public:
-    static RawPtr<WorkerRuntimeAgent> create(V8Debugger* debugger, WorkerGlobalScope* context, InspectorRuntimeAgent::Client* client, int contextGroupId)
+    static RawPtr<WorkerRuntimeAgent> create(V8RuntimeAgent* agent, WorkerGlobalScope* context, InspectorRuntimeAgent::Client* client)
     {
-        return new WorkerRuntimeAgent(debugger, context, client, contextGroupId);
+        return new WorkerRuntimeAgent(agent, context, client);
     }
     ~WorkerRuntimeAgent() override;
     DECLARE_VIRTUAL_TRACE();
@@ -50,7 +50,7 @@
     void enable(ErrorString*) final;
 
 private:
-    WorkerRuntimeAgent(V8Debugger*, WorkerGlobalScope*, InspectorRuntimeAgent::Client*, int contextGroupId);
+    WorkerRuntimeAgent(V8RuntimeAgent*, WorkerGlobalScope*, InspectorRuntimeAgent::Client*);
 
     Member<WorkerGlobalScope> m_workerGlobalScope;
 };
diff --git a/third_party/WebKit/Source/core/layout/HitTestCache.h b/third_party/WebKit/Source/core/layout/HitTestCache.h
index f429566..304afb16 100644
--- a/third_party/WebKit/Source/core/layout/HitTestCache.h
+++ b/third_party/WebKit/Source/core/layout/HitTestCache.h
@@ -37,7 +37,7 @@
 class CORE_EXPORT HitTestCache final : public GarbageCollectedFinalized<HitTestCache> {
     WTF_MAKE_NONCOPYABLE(HitTestCache);
 public:
-    static RawPtr<HitTestCache> create()
+    static HitTestCache* create()
     {
         return new HitTestCache;
     }
diff --git a/third_party/WebKit/Source/core/layout/LayoutBlockFlowLine.cpp b/third_party/WebKit/Source/core/layout/LayoutBlockFlowLine.cpp
index 0138337..2fa89d39 100644
--- a/third_party/WebKit/Source/core/layout/LayoutBlockFlowLine.cpp
+++ b/third_party/WebKit/Source/core/layout/LayoutBlockFlowLine.cpp
@@ -39,8 +39,8 @@
 #include "core/layout/line/LineWidth.h"
 #include "core/layout/line/WordMeasurement.h"
 #include "core/layout/svg/line/SVGRootInlineBox.h"
-#include "platform/fonts/Character.h"
 #include "platform/text/BidiResolver.h"
+#include "platform/text/Character.h"
 #include "wtf/StdLibExtras.h"
 #include "wtf/Vector.h"
 #include "wtf/text/CharacterNames.h"
diff --git a/third_party/WebKit/Source/core/layout/LayoutGrid.cpp b/third_party/WebKit/Source/core/layout/LayoutGrid.cpp
index 9710729..cfb0a74 100644
--- a/third_party/WebKit/Source/core/layout/LayoutGrid.cpp
+++ b/third_party/WebKit/Source/core/layout/LayoutGrid.cpp
@@ -247,6 +247,9 @@
 
     LayoutUnit& freeSpaceForDirection(GridTrackSizingDirection direction) { return direction == ForColumns ? freeSpaceForColumns : freeSpaceForRows; }
 
+    enum SizingOperation { TrackSizing, IntrinsicSizeComputation };
+    SizingOperation sizingOperation { TrackSizing };
+
 private:
     LayoutUnit freeSpaceForColumns { };
     LayoutUnit freeSpaceForRows { };
@@ -330,6 +333,7 @@
 {
     ASSERT(freeSpace >= 0);
     sizingData.freeSpaceForDirection(direction) = freeSpace - guttersSize(direction, direction == ForRows ? gridRowCount() : gridColumnCount());
+    sizingData.sizingOperation = GridSizingData::TrackSizing;
 
     LayoutUnit baseSizes, growthLimits;
     computeUsedBreadthOfGridTracks(direction, sizingData, baseSizes, growthLimits, AvailableSpaceDefinite);
@@ -419,6 +423,7 @@
 
     GridSizingData sizingData(gridColumnCount(), gridRowCount());
     sizingData.freeSpaceForDirection(ForColumns) = LayoutUnit();
+    sizingData.sizingOperation = GridSizingData::IntrinsicSizeComputation;
     const_cast<LayoutGrid*>(this)->computeUsedBreadthOfGridTracks(ForColumns, sizingData, minLogicalWidth, maxLogicalWidth, AvailableSpaceIndefinite);
 
     LayoutUnit totalGuttersSize = guttersSize(ForColumns, sizingData.columnTracks.size());
@@ -434,6 +439,7 @@
 {
     ASSERT(tracksAreWiderThanMinTrackBreadth(ForColumns, sizingData));
     sizingData.freeSpaceForDirection(ForRows) = LayoutUnit();
+    sizingData.sizingOperation = GridSizingData::IntrinsicSizeComputation;
     computeUsedBreadthOfGridTracks(ForRows, sizingData, m_minContentHeight, m_maxContentHeight, AvailableSpaceIndefinite);
 
     LayoutUnit totalGuttersSize = guttersSize(ForRows, gridRowCount());
@@ -683,10 +689,8 @@
 LayoutUnit LayoutGrid::logicalHeightForChild(LayoutBox& child, GridSizingData& sizingData)
 {
     SubtreeLayoutScope layoutScope(child);
-    LayoutUnit oldOverrideContainingBlockContentLogicalWidth = child.hasOverrideContainingBlockLogicalWidth() ? child.overrideContainingBlockContentLogicalWidth() : LayoutUnit();
-    LayoutUnit overrideContainingBlockContentLogicalWidth = gridAreaBreadthForChild(child, ForColumns, sizingData.columnTracks);
     bool shouldClearContainingBlockLogicalHeight = child.hasRelativeLogicalHeight() || child.styleRef().logicalHeight().isIntrinsicOrAuto();
-    if (shouldClearContainingBlockLogicalHeight || oldOverrideContainingBlockContentLogicalWidth != overrideContainingBlockContentLogicalWidth)
+    if (shouldClearContainingBlockLogicalHeight)
         layoutScope.setNeedsLayout(&child, LayoutInvalidationReason::GridChanged);
 
     bool hasOverrideHeight = child.hasOverrideLogicalContentHeight();
@@ -694,7 +698,6 @@
     if (hasOverrideHeight && child.needsLayout())
         child.clearOverrideLogicalContentHeight();
 
-    child.setOverrideContainingBlockContentLogicalWidth(overrideContainingBlockContentLogicalWidth);
     // If |child| has a relative logical height, we shouldn't let it override its intrinsic height, which is
     // what we are interested in here. Thus we need to set the override logical height to -1 (no possible resolution).
     if (shouldClearContainingBlockLogicalHeight)
@@ -717,10 +720,26 @@
     if (!childSize.isAuto() || childMinSize.isAuto())
         return minContentForChild(child, direction, sizingData);
 
-    if (isRowAxis)
-        return child.computeLogicalWidthUsing(MinSize, childMinSize, contentLogicalWidth(), this);
+    bool overrideLogicalWidthHasChanged = updateOverrideContainingBlockContentLogicalWidthForChild(child, sizingData);
+    if (isRowAxis) {
+        LayoutUnit marginLogicalWidth = sizingData.sizingOperation == GridSizingData::TrackSizing ? computeMarginLogicalSizeForChild(InlineDirection, child) : marginIntrinsicLogicalWidthForChild(child);
+        return child.computeLogicalWidthUsing(MinSize, childMinSize, child.overrideContainingBlockContentLogicalWidth(), this) + marginLogicalWidth;
+    }
 
-    return child.computeLogicalHeightUsing(MinSize, childMinSize, child.intrinsicLogicalHeight()) + child.scrollbarLogicalHeight();
+    if (overrideLogicalWidthHasChanged)
+        child.setNeedsLayout(LayoutInvalidationReason::GridChanged);
+    child.layoutIfNeeded();
+    return child.computeLogicalHeightUsing(MinSize, childMinSize, child.intrinsicLogicalHeight()) + child.marginLogicalHeight() + child.scrollbarLogicalHeight();
+}
+
+bool LayoutGrid::updateOverrideContainingBlockContentLogicalWidthForChild(LayoutBox& child, GridSizingData& sizingData)
+{
+    LayoutUnit overrideWidth = gridAreaBreadthForChild(child, ForColumns, sizingData.columnTracks);
+    if (child.hasOverrideContainingBlockLogicalWidth() && child.overrideContainingBlockContentLogicalWidth() == overrideWidth)
+        return false;
+
+    child.setOverrideContainingBlockContentLogicalWidth(overrideWidth);
+    return true;
 }
 
 LayoutUnit LayoutGrid::minContentForChild(LayoutBox& child, GridTrackSizingDirection direction, GridSizingData& sizingData)
@@ -741,6 +760,9 @@
         return child.minPreferredLogicalWidth() + marginIntrinsicLogicalWidthForChild(child);
     }
 
+    SubtreeLayoutScope layouter(child);
+    if (updateOverrideContainingBlockContentLogicalWidthForChild(child, sizingData))
+        child.setNeedsLayout(LayoutInvalidationReason::GridChanged);
     return logicalHeightForChild(child, sizingData);
 }
 
@@ -762,6 +784,9 @@
         return child.maxPreferredLogicalWidth() + marginIntrinsicLogicalWidthForChild(child);
     }
 
+    SubtreeLayoutScope layouter(child);
+    if (updateOverrideContainingBlockContentLogicalWidthForChild(child, sizingData))
+        child.setNeedsLayout(LayoutInvalidationReason::GridChanged);
     return logicalHeightForChild(child, sizingData);
 }
 
@@ -1616,6 +1641,9 @@
     // FIXME: This will affect the computed style value of grid tracks size, since we are
     // using these positions to compute them.
 
+    // The grid container's frame elements (border, padding and <content-position> offset) are sensible to the
+    // inline-axis flow direction. However, column lines positions are 'direction' unaware. This simplification
+    // allows us to use the same indexes to identify the columns independently on the inline-axis direction.
     unsigned numberOfTracks = sizingData.columnTracks.size();
     unsigned numberOfLines = numberOfTracks + 1;
     unsigned lastLine = numberOfLines - 1;
@@ -1624,7 +1652,7 @@
     LayoutUnit trackGap = guttersSize(ForColumns, 2);
     m_columnPositions.resize(numberOfLines);
     m_columnPositions[0] = borderAndPaddingStart() + offset.positionOffset;
-    for (unsigned i = 0; i < lastLine; ++i)
+    for (unsigned i = 0; i < nextToLastLine; ++i)
         m_columnPositions[i + 1] = m_columnPositions[i] + offset.distributionOffset + sizingData.columnTracks[i].baseSize() + trackGap;
     m_columnPositions[lastLine] = m_columnPositions[nextToLastLine] + sizingData.columnTracks[nextToLastLine].baseSize();
 
@@ -1636,7 +1664,7 @@
     trackGap = guttersSize(ForRows, 2);
     m_rowPositions.resize(numberOfLines);
     m_rowPositions[0] = borderAndPaddingBefore() + offset.positionOffset;
-    for (unsigned i = 0; i < lastLine; ++i)
+    for (unsigned i = 0; i < nextToLastLine; ++i)
         m_rowPositions[i + 1] = m_rowPositions[i] + offset.distributionOffset + sizingData.rowTracks[i].baseSize() + trackGap;
     m_rowPositions[lastLine] = m_rowPositions[nextToLastLine] + sizingData.rowTracks[nextToLastLine].baseSize();
 }
@@ -1667,18 +1695,21 @@
     return isHorizontalWritingMode() ? child.marginHeight() : child.marginWidth();
 }
 
-LayoutUnit LayoutGrid::computeMarginLogicalHeightForChild(const LayoutBox& child) const
+LayoutUnit LayoutGrid::computeMarginLogicalSizeForChild(MarginDirection forDirection, const LayoutBox& child) const
 {
     if (!child.styleRef().hasMargin())
         return LayoutUnit();
 
-    LayoutUnit marginBefore;
-    LayoutUnit marginAfter;
-    child.computeMarginsForDirection(BlockDirection, this, child.containingBlockLogicalWidthForContent(), child.logicalHeight(), marginBefore, marginAfter,
-        child.style()->marginBeforeUsing(style()),
-        child.style()->marginAfterUsing(style()));
+    bool isRowAxis = forDirection == InlineDirection;
+    LayoutUnit marginStart;
+    LayoutUnit marginEnd;
+    LayoutUnit logicalSize = isRowAxis ? child.logicalWidth() : child.logicalHeight();
+    Length marginStartLength = isRowAxis ? child.styleRef().marginStart() : child.styleRef().marginBeforeUsing(style());
+    Length marginEndLength = isRowAxis ? child.styleRef().marginEnd() : child.styleRef().marginAfterUsing(style());
+    child.computeMarginsForDirection(forDirection, this, child.containingBlockLogicalWidthForContent(), logicalSize,
+        marginStart, marginEnd, marginStartLength, marginEndLength);
 
-    return marginBefore + marginAfter;
+    return marginStart + marginEnd;
 }
 
 LayoutUnit LayoutGrid::availableAlignmentSpaceForChildBeforeStretching(LayoutUnit gridAreaBreadthForChild, const LayoutBox& child) const
@@ -1686,7 +1717,7 @@
     // Because we want to avoid multiple layouts, stretching logic might be performed before
     // children are laid out, so we can't use the child cached values. Hence, we need to
     // compute margins in order to determine the available height before stretching.
-    return gridAreaBreadthForChild - (child.needsLayout() ? computeMarginLogicalHeightForChild(child) : marginLogicalHeightForChild(child));
+    return gridAreaBreadthForChild - (child.needsLayout() ? computeMarginLogicalSizeForChild(BlockDirection, child) : marginLogicalHeightForChild(child));
 }
 
 // FIXME: This logic is shared by LayoutFlexibleBox, so it should be moved to LayoutBox.
diff --git a/third_party/WebKit/Source/core/layout/LayoutGrid.h b/third_party/WebKit/Source/core/layout/LayoutGrid.h
index 742eaa8..b9d3209 100644
--- a/third_party/WebKit/Source/core/layout/LayoutGrid.h
+++ b/third_party/WebKit/Source/core/layout/LayoutGrid.h
@@ -148,6 +148,7 @@
 
     GridTrackSize gridTrackSize(GridTrackSizingDirection, size_t) const;
 
+    bool updateOverrideContainingBlockContentLogicalWidthForChild(LayoutBox&, GridSizingData&);
     LayoutUnit logicalHeightForChild(LayoutBox&, GridSizingData&);
     LayoutUnit minSizeForChild(LayoutBox&, GridTrackSizingDirection, GridSizingData&);
     LayoutUnit minContentForChild(LayoutBox&, GridTrackSizingDirection, GridSizingData&);
@@ -169,7 +170,7 @@
     void paintChildren(const PaintInfo&, const LayoutPoint&) const override;
 
     LayoutUnit marginLogicalHeightForChild(const LayoutBox&) const;
-    LayoutUnit computeMarginLogicalHeightForChild(const LayoutBox&) const;
+    LayoutUnit computeMarginLogicalSizeForChild(MarginDirection, const LayoutBox&) const;
     LayoutUnit availableAlignmentSpaceForChildBeforeStretching(LayoutUnit gridAreaBreadthForChild, const LayoutBox&) const;
     void applyStretchAlignmentToChildIfNeeded(LayoutBox&);
     bool hasAutoMarginsInColumnAxis(const LayoutBox&) const;
diff --git a/third_party/WebKit/Source/core/layout/LayoutImage.cpp b/third_party/WebKit/Source/core/layout/LayoutImage.cpp
index d0d5380..c4def60 100644
--- a/third_party/WebKit/Source/core/layout/LayoutImage.cpp
+++ b/third_party/WebKit/Source/core/layout/LayoutImage.cpp
@@ -85,7 +85,7 @@
         intrinsicSizeChanged();
 }
 
-void LayoutImage::setImageResource(RawPtr<LayoutImageResource> imageResource)
+void LayoutImage::setImageResource(LayoutImageResource* imageResource)
 {
     ASSERT(!m_imageResource);
     m_imageResource = imageResource;
diff --git a/third_party/WebKit/Source/core/layout/LayoutImage.h b/third_party/WebKit/Source/core/layout/LayoutImage.h
index b42aa49..ba41cea4 100644
--- a/third_party/WebKit/Source/core/layout/LayoutImage.h
+++ b/third_party/WebKit/Source/core/layout/LayoutImage.h
@@ -55,7 +55,7 @@
 
     static LayoutImage* createAnonymous(Document*);
 
-    void setImageResource(RawPtr<LayoutImageResource>);
+    void setImageResource(LayoutImageResource*);
 
     LayoutImageResource* imageResource() { return m_imageResource.get(); }
     const LayoutImageResource* imageResource() const { return m_imageResource.get(); }
diff --git a/third_party/WebKit/Source/core/layout/LayoutImageResource.h b/third_party/WebKit/Source/core/layout/LayoutImageResource.h
index b98509b..c2cd662 100644
--- a/third_party/WebKit/Source/core/layout/LayoutImageResource.h
+++ b/third_party/WebKit/Source/core/layout/LayoutImageResource.h
@@ -38,7 +38,7 @@
 public:
     virtual ~LayoutImageResource();
 
-    static RawPtr<LayoutImageResource> create()
+    static LayoutImageResource* create()
     {
         return new LayoutImageResource;
     }
diff --git a/third_party/WebKit/Source/core/layout/LayoutImageResourceStyleImage.h b/third_party/WebKit/Source/core/layout/LayoutImageResourceStyleImage.h
index 986fec2..8f4da9b 100644
--- a/third_party/WebKit/Source/core/layout/LayoutImageResourceStyleImage.h
+++ b/third_party/WebKit/Source/core/layout/LayoutImageResourceStyleImage.h
@@ -38,7 +38,7 @@
 public:
     ~LayoutImageResourceStyleImage() override;
 
-    static RawPtr<LayoutImageResource> create(StyleImage* styleImage)
+    static LayoutImageResource* create(StyleImage* styleImage)
     {
         return new LayoutImageResourceStyleImage(styleImage);
     }
diff --git a/third_party/WebKit/Source/core/layout/LayoutPart.cpp b/third_party/WebKit/Source/core/layout/LayoutPart.cpp
index 5f09d972..81945b7 100644
--- a/third_party/WebKit/Source/core/layout/LayoutPart.cpp
+++ b/third_party/WebKit/Source/core/layout/LayoutPart.cpp
@@ -342,7 +342,6 @@
         return false;
 
     RefPtr<LayoutPart> protector(this);
-    RawPtr<Node> protectedNode(node());
     widget->setFrameRect(newFrame);
     return widget->frameRect().size() != newFrame.size();
 }
diff --git a/third_party/WebKit/Source/core/layout/LayoutPartTest.cpp b/third_party/WebKit/Source/core/layout/LayoutPartTest.cpp
index 7944c14..084c42c5 100644
--- a/third_party/WebKit/Source/core/layout/LayoutPartTest.cpp
+++ b/third_party/WebKit/Source/core/layout/LayoutPartTest.cpp
@@ -23,8 +23,8 @@
 
 TEST_F(LayoutPartTest, DestroyUpdatesImageQualityController)
 {
-    RawPtr<Element> element = HTMLElement::create(HTMLNames::divTag, document());
-    LayoutObject* part = new OverriddenLayoutPart(element.get());
+    Element* element = HTMLElement::create(HTMLNames::divTag, document());
+    LayoutObject* part = new OverriddenLayoutPart(element);
     // The third and forth arguments are not important in this test.
     ImageQualityController::imageQualityController()->set(*part, 0, this, LayoutSize(1, 1), false);
     EXPECT_TRUE(ImageQualityController::has(*part));
diff --git a/third_party/WebKit/Source/core/layout/LayoutScrollbar.cpp b/third_party/WebKit/Source/core/layout/LayoutScrollbar.cpp
index f4459b9..862d7ff 100644
--- a/third_party/WebKit/Source/core/layout/LayoutScrollbar.cpp
+++ b/third_party/WebKit/Source/core/layout/LayoutScrollbar.cpp
@@ -36,7 +36,7 @@
 
 namespace blink {
 
-RawPtr<Scrollbar> LayoutScrollbar::createCustomScrollbar(ScrollableArea* scrollableArea, ScrollbarOrientation orientation, Node* ownerNode, LocalFrame* owningFrame)
+Scrollbar* LayoutScrollbar::createCustomScrollbar(ScrollableArea* scrollableArea, ScrollbarOrientation orientation, Node* ownerNode, LocalFrame* owningFrame)
 {
     return new LayoutScrollbar(scrollableArea, orientation, ownerNode, owningFrame);
 }
diff --git a/third_party/WebKit/Source/core/layout/LayoutScrollbar.h b/third_party/WebKit/Source/core/layout/LayoutScrollbar.h
index 2af04b8..cf01737 100644
--- a/third_party/WebKit/Source/core/layout/LayoutScrollbar.h
+++ b/third_party/WebKit/Source/core/layout/LayoutScrollbar.h
@@ -43,7 +43,7 @@
 
 class LayoutScrollbar final : public Scrollbar {
 public:
-    static RawPtr<Scrollbar> createCustomScrollbar(ScrollableArea*, ScrollbarOrientation, Node*, LocalFrame* owningFrame = nullptr);
+    static Scrollbar* createCustomScrollbar(ScrollableArea*, ScrollbarOrientation, Node*, LocalFrame* owningFrame = nullptr);
     ~LayoutScrollbar() override;
 
     LayoutBox* owningLayoutObject() const;
diff --git a/third_party/WebKit/Source/core/layout/LayoutTestHelper.cpp b/third_party/WebKit/Source/core/layout/LayoutTestHelper.cpp
index 0ea264d..d1b4ac06 100644
--- a/third_party/WebKit/Source/core/layout/LayoutTestHelper.cpp
+++ b/third_party/WebKit/Source/core/layout/LayoutTestHelper.cpp
@@ -10,7 +10,7 @@
 
 namespace blink {
 
-RenderingTest::RenderingTest(RawPtr<FrameLoaderClient> frameLoaderClient)
+RenderingTest::RenderingTest(FrameLoaderClient* frameLoaderClient)
     : m_frameLoaderClient(frameLoaderClient) { }
 
 void RenderingTest::SetUp()
diff --git a/third_party/WebKit/Source/core/layout/LayoutTestHelper.h b/third_party/WebKit/Source/core/layout/LayoutTestHelper.h
index 581a156a..a6c0c6c 100644
--- a/third_party/WebKit/Source/core/layout/LayoutTestHelper.h
+++ b/third_party/WebKit/Source/core/layout/LayoutTestHelper.h
@@ -23,7 +23,7 @@
 public:
     virtual FrameSettingOverrideFunction settingOverrider() const { return nullptr; }
 
-    RenderingTest(RawPtr<FrameLoaderClient> = nullptr);
+    RenderingTest(FrameLoaderClient* = nullptr);
 
 protected:
     void SetUp() override;
@@ -65,7 +65,7 @@
 
 class SingleChildFrameLoaderClient final : public EmptyFrameLoaderClient {
 public:
-    static RawPtr<SingleChildFrameLoaderClient> create() { return new SingleChildFrameLoaderClient; }
+    static SingleChildFrameLoaderClient* create() { return new SingleChildFrameLoaderClient; }
 
     DEFINE_INLINE_VIRTUAL_TRACE()
     {
@@ -86,7 +86,7 @@
 
 class FrameLoaderClientWithParent final : public EmptyFrameLoaderClient {
 public:
-    static RawPtr<FrameLoaderClientWithParent> create(Frame* parent)
+    static FrameLoaderClientWithParent* create(Frame* parent)
     {
         return new FrameLoaderClientWithParent(parent);
     }
diff --git a/third_party/WebKit/Source/core/layout/LayoutText.cpp b/third_party/WebKit/Source/core/layout/LayoutText.cpp
index aa4c3149..f1e723f 100644
--- a/third_party/WebKit/Source/core/layout/LayoutText.cpp
+++ b/third_party/WebKit/Source/core/layout/LayoutText.cpp
@@ -41,10 +41,10 @@
 #include "core/layout/line/InlineTextBox.h"
 #include "core/paint/PaintLayer.h"
 #include "platform/LayoutTestSupport.h"
-#include "platform/fonts/Character.h"
 #include "platform/fonts/FontCache.h"
 #include "platform/geometry/FloatQuad.h"
 #include "platform/text/BidiResolver.h"
+#include "platform/text/Character.h"
 #include "platform/text/TextBreakIterator.h"
 #include "platform/text/TextRunIterator.h"
 #include "wtf/text/CharacterNames.h"
diff --git a/third_party/WebKit/Source/core/layout/LayoutTreeAsText.cpp b/third_party/WebKit/Source/core/layout/LayoutTreeAsText.cpp
index c897e7ad..81b4c02 100644
--- a/third_party/WebKit/Source/core/layout/LayoutTreeAsText.cpp
+++ b/third_party/WebKit/Source/core/layout/LayoutTreeAsText.cpp
@@ -825,8 +825,6 @@
 
 String counterValueForElement(Element* element)
 {
-    // Make sure the element is not freed during the layout.
-    RawPtr<Element> protector(element);
     element->document().updateLayout();
     TextStream stream;
     bool isFirstCounter = true;
@@ -840,8 +838,6 @@
 
 String markerTextForListItem(Element* element)
 {
-    // Make sure the element is not freed during the layout.
-    RawPtr<Element> protector(element);
     element->document().updateLayout();
 
     LayoutObject* layoutObject = element->layoutObject();
diff --git a/third_party/WebKit/Source/core/layout/TextAutosizer.cpp b/third_party/WebKit/Source/core/layout/TextAutosizer.cpp
index a8cbf69..cc41329 100644
--- a/third_party/WebKit/Source/core/layout/TextAutosizer.cpp
+++ b/third_party/WebKit/Source/core/layout/TextAutosizer.cpp
@@ -54,7 +54,7 @@
 #ifdef AUTOSIZING_DOM_DEBUG_INFO
 class WriteDebugInfoTask : public ExecutionContextTask {
 public:
-    WriteDebugInfoTask(RawPtr<Element> element, AtomicString value)
+    WriteDebugInfoTask(Element* element, AtomicString value)
         : m_element(element)
         , m_value(value)
     {
diff --git a/third_party/WebKit/Source/core/layout/TextAutosizer.h b/third_party/WebKit/Source/core/layout/TextAutosizer.h
index 4991908..4bb95ba 100644
--- a/third_party/WebKit/Source/core/layout/TextAutosizer.h
+++ b/third_party/WebKit/Source/core/layout/TextAutosizer.h
@@ -54,7 +54,7 @@
 class CORE_EXPORT TextAutosizer final : public GarbageCollectedFinalized<TextAutosizer> {
     WTF_MAKE_NONCOPYABLE(TextAutosizer);
 public:
-    static RawPtr<TextAutosizer> create(const Document* document)
+    static TextAutosizer* create(const Document* document)
     {
         return new TextAutosizer(document);
     }
diff --git a/third_party/WebKit/Source/core/layout/line/BreakingContextInlineHeaders.h b/third_party/WebKit/Source/core/layout/line/BreakingContextInlineHeaders.h
index 4f3b643..b8f2a40 100644
--- a/third_party/WebKit/Source/core/layout/line/BreakingContextInlineHeaders.h
+++ b/third_party/WebKit/Source/core/layout/line/BreakingContextInlineHeaders.h
@@ -100,8 +100,8 @@
     void handleReplaced();
     bool handleText(WordMeasurements&, bool& hyphenated);
     void prepareForNextCharacter(const LineLayoutText&, bool& prohibitBreakInside, bool previousCharacterIsSpace);
-    bool canBreakAtWhitespace(bool breakWords, WordMeasurement&, bool stoppedIgnoringSpaces, bool& hyphenated, float charWidth, float& hyphenWidth, bool betweenWords, bool midWordBreak, bool breakAll, bool previousCharacterIsSpace, float lastWidthMeasurement, const LineLayoutText&, const Font&, bool applyWordSpacing, float wordSpacing);
-    bool trailingSpaceExceedsAvailableWidth(bool midWordBreak, const LineLayoutText&, WordMeasurement&, bool applyWordSpacing, bool wordSpacing, const Font&);
+    bool canBreakAtWhitespace(bool breakWords, WordMeasurement&, bool stoppedIgnoringSpaces, bool& hyphenated, float charWidth, float& hyphenWidth, bool betweenWords, bool midWordBreak, bool canBreakMidWord, bool previousCharacterIsSpace, float lastWidthMeasurement, const LineLayoutText&, const Font&, bool applyWordSpacing, float wordSpacing);
+    bool trailingSpaceExceedsAvailableWidth(bool canBreakMidWord, const LineLayoutText&, WordMeasurement&, bool applyWordSpacing, bool wordSpacing, const Font&);
     WordMeasurement& calculateWordWidth(WordMeasurements&, LineLayoutText&, unsigned lastSpace, float& lastWidthMeasurement, float wordSpacingForWordMeasurement, const Font&, float wordTrailingSpaceWidth, UChar);
     void stopIgnoringSpaces(unsigned& lastSpace);
     void commitAndUpdateLineBreakIfNeeded();
@@ -115,6 +115,9 @@
 
 private:
     void skipTrailingWhitespace(InlineIterator&, const LineInfo&);
+    bool rewindToMidWordBreak(WordMeasurement&, int end, float width);
+    bool rewindToFirstMidWordBreak(LineLayoutText, const ComputedStyle&, const Font&, bool breakAll, WordMeasurement&);
+    bool rewindToMidWordBreak(LineLayoutText, const ComputedStyle&, const Font&, bool breakAll, WordMeasurement&);
 
     InlineBidiResolver& m_resolver;
 
@@ -539,6 +542,102 @@
     return font.width(run, fallbackFonts, glyphBounds);
 }
 
+ALWAYS_INLINE int lastBreakablePositionForBreakAll(LineLayoutText text,
+    const ComputedStyle& style, int start, int end)
+{
+    LazyLineBreakIterator lineBreakIterator(text.text(), style.locale());
+    int lastBreakablePosition = 0, nextBreakablePosition = -1;
+    for (int i = start; ;i = nextBreakablePosition + 1) {
+        lineBreakIterator.isBreakable(i, nextBreakablePosition, LineBreakType::BreakAll);
+        if (nextBreakablePosition == end)
+            return end;
+        if (nextBreakablePosition < 0 || nextBreakablePosition > end)
+            return lastBreakablePosition;
+        lastBreakablePosition = nextBreakablePosition;
+    }
+}
+
+ALWAYS_INLINE bool BreakingContext::rewindToMidWordBreak(
+    WordMeasurement& wordMeasurement, int end, float width)
+{
+    wordMeasurement.endOffset = end;
+    wordMeasurement.width = width;
+
+    m_current.moveTo(m_current.getLineLayoutItem(), end);
+    m_lineBreak.moveTo(m_current.getLineLayoutItem(), m_current.offset());
+    return true;
+}
+
+ALWAYS_INLINE bool BreakingContext::rewindToFirstMidWordBreak(LineLayoutText text,
+    const ComputedStyle& style, const Font& font, bool breakAll,
+    WordMeasurement& wordMeasurement)
+{
+    int start = wordMeasurement.startOffset;
+    int end;
+    if (breakAll) {
+        LazyLineBreakIterator lineBreakIterator(text.text(), style.locale());
+        end = -1;
+        lineBreakIterator.isBreakable(start + 1, end, LineBreakType::BreakAll);
+        if (end < 0)
+            return false;
+    } else {
+        end = start + 1;
+    }
+    if (end >= wordMeasurement.endOffset)
+        return false;
+
+    float width = textWidth(text, start, end - start, font, m_width.currentWidth(), m_collapseWhiteSpace);
+    return rewindToMidWordBreak(wordMeasurement, end, width);
+}
+
+ALWAYS_INLINE bool BreakingContext::rewindToMidWordBreak(LineLayoutText text,
+    const ComputedStyle& style, const Font& font, bool breakAll,
+    WordMeasurement& wordMeasurement)
+{
+    int start = wordMeasurement.startOffset;
+    int len = wordMeasurement.endOffset - start;
+    if (!len)
+        return false;
+    if (m_width.availableWidth() <= LayoutUnit::epsilon())
+        return rewindToFirstMidWordBreak(text, style, font, breakAll, wordMeasurement);
+
+    TextRun run = constructTextRun(font, text, start, len, style);
+    run.setTabSize(!m_collapseWhiteSpace, style.getTabSize());
+    run.setXPos(m_width.currentWidth());
+
+    // TODO(kojii): should be replaced with safe-to-break when hb is ready.
+    float x = m_width.availableWidth() + LayoutUnit::epsilon() - m_width.currentWidth();
+    len = font.offsetForPosition(run, x, false);
+    if (!len && !m_width.currentWidth())
+        return rewindToFirstMidWordBreak(text, style, font, breakAll, wordMeasurement);
+
+    FloatRect rect = font.selectionRectForText(run, FloatPoint(), 0, 0, len);
+    // HarfBuzzShaper ignores includePartialGlyphs=false, so we need to find the
+    // real width that fits. Usually a few loops at maximum.
+    if (len && !m_width.fitsOnLine(rect.width())) {
+        for (; ; ) {
+            --len;
+            if (!len) {
+                rect.setWidth(0);
+                break;
+            }
+            rect = font.selectionRectForText(run, FloatPoint(), 0, 0, len);
+            if (m_width.fitsOnLine(rect.width()))
+                break;
+        }
+    }
+
+    int end = start + len;
+    if (breakAll) {
+        end = lastBreakablePositionForBreakAll(text, style, start, end);
+        if (!end)
+            return false;
+        rect = font.selectionRectForText(run, FloatPoint(), 0, 0, end - start);
+    }
+
+    return rewindToMidWordBreak(wordMeasurement, end, rect.width());
+}
+
 inline bool BreakingContext::handleText(WordMeasurements& wordMeasurements, bool& hyphenated)
 {
     if (!m_current.offset())
@@ -561,12 +660,10 @@
     float lastSpaceWordSpacing = 0;
     float wordSpacingForWordMeasurement = 0;
 
-    float widthFromLastBreakingOpportunity = m_width.uncommittedWidth();
     float charWidth = 0;
     // Auto-wrapping text should wrap in the middle of a word only if it could not wrap before the word,
     // which is only possible if the word is the first thing on the line, that is, if |w| is zero.
     bool breakWords = m_currentStyle->breakWords() && ((m_autoWrap && !m_width.committedWidth()) || m_currWS == PRE);
-    bool midWordBreak = false;
     bool breakAll = m_currentStyle->wordBreak() == BreakAllWordBreak && m_autoWrap;
     bool keepAll = m_currentStyle->wordBreak() == KeepAllWordBreak && m_autoWrap;
     bool prohibitBreakInside = m_currentStyle->hasTextCombine() && layoutText.isCombineText() && LineLayoutTextCombine(layoutText).isCombined();
@@ -585,6 +682,11 @@
         keepAll = false;
     }
 
+    // Use LineBreakType::Normal for break-all. When a word does not fit,
+    // rewindToMidWordBreak() finds the mid-word break point.
+    LineBreakType lineBreakType = keepAll ? LineBreakType::KeepAll : LineBreakType::Normal;
+    bool canBreakMidWord = breakAll || breakWords;
+
     if (layoutText.isWordBreak()) {
         m_width.commit();
         m_lineBreak.moveToStartOf(m_current.getLineLayoutItem());
@@ -624,21 +726,13 @@
 
         bool applyWordSpacing = false;
 
-        // Determine if we should try breaking in the middle of a word.
-        if (breakWords && !midWordBreak && !U16_IS_TRAIL(c)) {
-            widthFromLastBreakingOpportunity += charWidth;
-            bool midWordBreakIsBeforeSurrogatePair = U16_IS_LEAD(c) && m_current.offset() + 1 < layoutText.textLength() && U16_IS_TRAIL(layoutText.uncheckedCharacterAt(m_current.offset() + 1));
-            charWidth = textWidth(layoutText, m_current.offset(), midWordBreakIsBeforeSurrogatePair ? 2 : 1, font, m_width.committedWidth() + widthFromLastBreakingOpportunity, m_collapseWhiteSpace);
-            midWordBreak = m_width.committedWidth() + widthFromLastBreakingOpportunity + charWidth > m_width.availableWidth();
-        }
-
         // Determine if we are in the whitespace between words.
         int nextBreakablePosition = m_current.nextBreakablePosition();
-        bool betweenWords = c == newlineCharacter || (m_currWS != PRE && !m_atStart && m_layoutTextInfo.m_lineBreakIterator.isBreakable(m_current.offset(), nextBreakablePosition, breakAll ? LineBreakType::BreakAll : keepAll ? LineBreakType::KeepAll : LineBreakType::Normal));
+        bool betweenWords = c == newlineCharacter || (m_currWS != PRE && !m_atStart && m_layoutTextInfo.m_lineBreakIterator.isBreakable(m_current.offset(), nextBreakablePosition, lineBreakType));
         m_current.setNextBreakablePosition(nextBreakablePosition);
 
         // If we're in the middle of a word or at the start of a new one and can't break there, then continue to the next character.
-        if (!betweenWords && !midWordBreak) {
+        if (!betweenWords) {
             if (m_ignoringSpaces) {
                 // Stop ignoring spaces and begin at this
                 // new point.
@@ -676,6 +770,14 @@
         float lastWidthMeasurement;
         WordMeasurement& wordMeasurement = calculateWordWidth(wordMeasurements, layoutText, lastSpace, lastWidthMeasurement, wordSpacingForWordMeasurement, font, wordTrailingSpaceWidth, c);
         lastWidthMeasurement += lastSpaceWordSpacing;
+
+        bool midWordBreak = false;
+        if (canBreakMidWord && !m_width.fitsOnLine(lastWidthMeasurement)
+            && rewindToMidWordBreak(layoutText, style, font, breakAll, wordMeasurement)) {
+            lastWidthMeasurement = wordMeasurement.width;
+            midWordBreak = true;
+        }
+
         m_width.addUncommittedWidth(lastWidthMeasurement);
 
         // We keep track of the total width contributed by trailing space as we often want to exclude it when determining
@@ -691,15 +793,13 @@
             m_appliedStartWidth = true;
         }
 
-        applyWordSpacing = wordSpacing && m_currentCharacterIsSpace;
-
         // If we haven't hit a breakable position yet and already don't fit on the line try to move below any floats.
         if (!m_width.committedWidth() && m_autoWrap && !m_width.fitsOnLine() && !widthMeasurementAtLastBreakOpportunity)
             m_width.fitBelowFloats(m_lineInfo.isFirstLine());
 
         // If there is a soft-break available at this whitespace position then take it.
         applyWordSpacing = wordSpacing && m_currentCharacterIsSpace;
-        if (canBreakAtWhitespace(breakWords, wordMeasurement, stoppedIgnoringSpaces, hyphenated, charWidth, hyphenWidth, betweenWords, midWordBreak, breakAll, previousCharacterIsSpace, lastWidthMeasurement, layoutText, font, applyWordSpacing, wordSpacing))
+        if (canBreakAtWhitespace(breakWords, wordMeasurement, stoppedIgnoringSpaces, hyphenated, charWidth, hyphenWidth, betweenWords, midWordBreak, canBreakMidWord, previousCharacterIsSpace, lastWidthMeasurement, layoutText, font, applyWordSpacing, wordSpacing))
             return false;
 
         // If there is a hard-break available at this whitespace position then take it.
@@ -716,22 +816,16 @@
         // opportunity to break after a word.
         if (m_autoWrap && betweenWords) {
             m_width.commit();
-            widthFromLastBreakingOpportunity = 0;
             m_lineBreak.moveTo(m_current.getLineLayoutItem(), m_current.offset(), m_current.nextBreakablePosition());
             breakWords = false;
+            canBreakMidWord = breakAll;
             widthMeasurementAtLastBreakOpportunity = lastWidthMeasurement;
         }
 
-        // Remember this as a breakable position in case adding the end width forces a break.
-        if (midWordBreak && !U16_IS_TRAIL(c) && !(WTF::Unicode::category(c) & (WTF::Unicode::Mark_NonSpacing | WTF::Unicode::Mark_Enclosing | WTF::Unicode::Mark_SpacingCombining))) {
-            m_lineBreak.moveTo(m_current.getLineLayoutItem(), m_current.offset(), m_current.nextBreakablePosition());
-            midWordBreak &= (breakWords || breakAll);
-        }
-
         if (betweenWords) {
             lastSpaceWordSpacing = applyWordSpacing ? wordSpacing : 0;
             wordSpacingForWordMeasurement = (applyWordSpacing && wordMeasurement.width) ? wordSpacing : 0;
-            lastSpace = !breakAll || m_currentCharacterIsSpace ? m_current.offset() : lastSpace;
+            lastSpace = m_current.offset();
         }
 
         // If we encounter a newline, or if we encounter a second space, we need to go ahead and break up
@@ -762,10 +856,17 @@
     float lastWidthMeasurement = 0;
     wordMeasurement.startOffset = lastSpace;
     wordMeasurement.endOffset = m_current.offset();
+    bool midWordBreak = false;
     if (!m_ignoringSpaces) {
         lastWidthMeasurement = textWidth(layoutText, lastSpace, m_current.offset() - lastSpace, font, m_width.currentWidth(), m_collapseWhiteSpace, &wordMeasurement.fallbackFonts, &wordMeasurement.glyphBounds);
         wordMeasurement.width = lastWidthMeasurement + wordSpacingForWordMeasurement;
         wordMeasurement.glyphBounds.move(wordSpacingForWordMeasurement, 0);
+
+        if (canBreakMidWord && !m_width.fitsOnLine(lastWidthMeasurement)
+            && rewindToMidWordBreak(layoutText, style, font, breakAll, wordMeasurement)) {
+            lastWidthMeasurement = wordMeasurement.width;
+            midWordBreak = true;
+        }
     }
     lastWidthMeasurement += lastSpaceWordSpacing;
 
@@ -777,16 +878,13 @@
 
     m_includeEndWidth = false;
 
-    if (!m_width.fitsOnLine()) {
-        if (breakAll && widthMeasurementAtLastBreakOpportunity) {
-            m_width.addUncommittedWidth(widthMeasurementAtLastBreakOpportunity);
-            m_width.commit();
-            return true;
-        }
-        if (!hyphenated && m_lineBreak.previousInSameNode() == softHyphenCharacter) {
-            hyphenated = true;
-            m_atEnd = true;
-        }
+    if (midWordBreak) {
+        m_width.commit();
+        m_atEnd = true;
+    } else if (!m_width.fitsOnLine() && !hyphenated
+        && m_lineBreak.previousInSameNode() == softHyphenCharacter) {
+        hyphenated = true;
+        m_atEnd = true;
     }
     return false;
 }
@@ -842,11 +940,11 @@
     return wordMeasurement;
 }
 
-inline bool BreakingContext::trailingSpaceExceedsAvailableWidth(bool midWordBreak, const LineLayoutText& layoutText, WordMeasurement& wordMeasurement, bool applyWordSpacing, bool wordSpacing, const Font& font)
+inline bool BreakingContext::trailingSpaceExceedsAvailableWidth(bool canBreakMidWord, const LineLayoutText& layoutText, WordMeasurement& wordMeasurement, bool applyWordSpacing, bool wordSpacing, const Font& font)
 {
     // If we break only after white-space, consider the current character
     // as candidate width for this line.
-    if (m_width.fitsOnLine() && m_currentCharacterIsSpace && m_currentStyle->breakOnlyAfterWhiteSpace() && !midWordBreak) {
+    if (m_width.fitsOnLine() && m_currentCharacterIsSpace && m_currentStyle->breakOnlyAfterWhiteSpace() && !canBreakMidWord) {
         float charWidth = textWidth(layoutText, m_current.offset(), 1, font, m_width.currentWidth(), m_collapseWhiteSpace, &wordMeasurement.fallbackFonts, &wordMeasurement.glyphBounds) + (applyWordSpacing ? wordSpacing : 0);
         // Check if line is too big even without the extra space
         // at the end of the line. If it is not, do nothing.
@@ -862,14 +960,16 @@
     return false;
 }
 
-inline bool BreakingContext::canBreakAtWhitespace(bool breakWords, WordMeasurement& wordMeasurement, bool stoppedIgnoringSpaces, bool& hyphenated, float charWidth, float& hyphenWidth, bool betweenWords, bool midWordBreak, bool breakAll, bool previousCharacterIsSpace, float lastWidthMeasurement, const LineLayoutText& layoutText, const Font& font, bool applyWordSpacing, float wordSpacing)
+inline bool BreakingContext::canBreakAtWhitespace(bool breakWords, WordMeasurement& wordMeasurement, bool stoppedIgnoringSpaces, bool& hyphenated, float charWidth, float& hyphenWidth, bool betweenWords, bool midWordBreak, bool canBreakMidWord, bool previousCharacterIsSpace, float lastWidthMeasurement, const LineLayoutText& layoutText, const Font& font, bool applyWordSpacing, float wordSpacing)
 {
     if (!m_autoWrap && !breakWords)
         return false;
 
     // If we break only after white-space, consider the current character
     // as candidate width for this line.
-    if (trailingSpaceExceedsAvailableWidth(midWordBreak, layoutText, wordMeasurement, applyWordSpacing, wordSpacing, font) || !m_width.fitsOnLine()) {
+    if (midWordBreak
+        || trailingSpaceExceedsAvailableWidth(canBreakMidWord, layoutText, wordMeasurement, applyWordSpacing, wordSpacing, font)
+        || !m_width.fitsOnLine()) {
         if (m_lineBreak.atTextParagraphSeparator()) {
             if (!stoppedIgnoringSpaces && m_current.offset() > 0)
                 m_lineMidpointState.ensureCharacterGetsLineBox(m_current);
@@ -891,7 +991,7 @@
             return true;
         }
     } else {
-        if (!betweenWords || (midWordBreak && !m_autoWrap) || (breakAll && !m_currentCharacterIsSpace))
+        if (!betweenWords || (midWordBreak && !m_autoWrap))
             m_width.addUncommittedWidth(-lastWidthMeasurement);
         if (hyphenWidth) {
             // Subtract the width of the soft hyphen out since we fit on a line.
diff --git a/third_party/WebKit/Source/core/layout/svg/LayoutSVGResourceFilter.h b/third_party/WebKit/Source/core/layout/svg/LayoutSVGResourceFilter.h
index 36d8f882..f977294 100644
--- a/third_party/WebKit/Source/core/layout/svg/LayoutSVGResourceFilter.h
+++ b/third_party/WebKit/Source/core/layout/svg/LayoutSVGResourceFilter.h
@@ -49,7 +49,7 @@
         PaintingFilterCycleDetected
     };
 
-    static RawPtr<FilterData> create()
+    static FilterData* create()
     {
         return new FilterData();
     }
@@ -90,7 +90,7 @@
     LayoutSVGResourceType resourceType() const override { return s_resourceType; }
 
     FilterData* getFilterDataForLayoutObject(const LayoutObject* object) { return m_filter.get(const_cast<LayoutObject*>(object)); }
-    void setFilterDataForLayoutObject(LayoutObject* object, RawPtr<FilterData> filterData) { m_filter.set(object, filterData); }
+    void setFilterDataForLayoutObject(LayoutObject* object, FilterData* filterData) { m_filter.set(object, filterData); }
 
 protected:
     void willBeDestroyed() override;
diff --git a/third_party/WebKit/Source/core/layout/svg/ReferenceFilterBuilder.cpp b/third_party/WebKit/Source/core/layout/svg/ReferenceFilterBuilder.cpp
index 73014d7..d7e26b8 100644
--- a/third_party/WebKit/Source/core/layout/svg/ReferenceFilterBuilder.cpp
+++ b/third_party/WebKit/Source/core/layout/svg/ReferenceFilterBuilder.cpp
@@ -69,7 +69,7 @@
 }
 #endif
 
-RawPtr<Filter> ReferenceFilterBuilder::build(float zoom, Element* element, FilterEffect* previousEffect, const ReferenceFilterOperation& filterOperation, const FloatSize* referenceBoxSize, const SkPaint* fillPaint, const SkPaint* strokePaint)
+Filter* ReferenceFilterBuilder::build(float zoom, Element* element, FilterEffect* previousEffect, const ReferenceFilterOperation& filterOperation, const FloatSize* referenceBoxSize, const SkPaint* fillPaint, const SkPaint* strokePaint)
 {
     TreeScope* treeScope = &element->treeScope();
 
@@ -102,7 +102,7 @@
     FloatRect referenceBox;
     if (referenceBoxSize) {
         referenceBox = FloatRect(FloatPoint(), *referenceBoxSize);
-    } else if (element->inDocument() && element->layoutObject() && element->layoutObject()->enclosingLayer()) {
+    } else if (element->inShadowIncludingDocument() && element->layoutObject() && element->layoutObject()->enclosingLayer()) {
         FloatSize size(element->layoutObject()->enclosingLayer()->physicalBoundingBoxIncludingReflectionAndStackingChildren(LayoutPoint()).size());
         referenceBox = FloatRect(FloatPoint(), size);
     }
@@ -110,15 +110,15 @@
     FloatRect filterRegion = SVGLengthContext::resolveRectangle<SVGFilterElement>(&filterElement, filterElement.filterUnits()->currentValue()->enumValue(), referenceBox);
     bool primitiveBoundingBoxMode = filterElement.primitiveUnits()->currentValue()->enumValue() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX;
     Filter::UnitScaling unitScaling = primitiveBoundingBoxMode ? Filter::BoundingBox : Filter::UserSpace;
-    RawPtr<Filter> result(Filter::create(referenceBox, filterRegion, zoom, unitScaling));
+    Filter* result = Filter::create(referenceBox, filterRegion, zoom, unitScaling);
     if (!previousEffect)
         previousEffect = result->getSourceGraphic();
 
     SVGFilterBuilder builder(previousEffect, nullptr, fillPaint, strokePaint);
-    builder.buildGraph(result.get(), filterElement, referenceBox);
+    builder.buildGraph(result, filterElement, referenceBox);
 
     result->setLastEffect(builder.lastEffect());
-    return result.release();
+    return result;
 }
 
 } // namespace blink
diff --git a/third_party/WebKit/Source/core/layout/svg/ReferenceFilterBuilder.h b/third_party/WebKit/Source/core/layout/svg/ReferenceFilterBuilder.h
index fb361557..a03c894 100644
--- a/third_party/WebKit/Source/core/layout/svg/ReferenceFilterBuilder.h
+++ b/third_party/WebKit/Source/core/layout/svg/ReferenceFilterBuilder.h
@@ -56,7 +56,7 @@
     static void clearDocumentResourceReference(const FilterOperation*);
 #endif
 
-    static RawPtr<Filter> build(float zoom, Element*, FilterEffect* previousEffect, const ReferenceFilterOperation&, const FloatSize* referenceBoxSize = nullptr, const SkPaint* fillPaint = nullptr, const SkPaint* strokePaint = nullptr);
+    static Filter* build(float zoom, Element*, FilterEffect* previousEffect, const ReferenceFilterOperation&, const FloatSize* referenceBoxSize = nullptr, const SkPaint* fillPaint = nullptr, const SkPaint* strokePaint = nullptr);
 };
 
 } // namespace blink
diff --git a/third_party/WebKit/Source/core/layout/svg/SVGLayoutTreeAsText.cpp b/third_party/WebKit/Source/core/layout/svg/SVGLayoutTreeAsText.cpp
index 67aca1c..e800cb7 100644
--- a/third_party/WebKit/Source/core/layout/svg/SVGLayoutTreeAsText.cpp
+++ b/third_party/WebKit/Source/core/layout/svg/SVGLayoutTreeAsText.cpp
@@ -506,9 +506,9 @@
         ts << "\n";
         // Creating a placeholder filter which is passed to the builder.
         FloatRect dummyRect;
-        RawPtr<Filter> dummyFilter = Filter::create(dummyRect, dummyRect, 1, Filter::BoundingBox);
+        Filter* dummyFilter = Filter::create(dummyRect, dummyRect, 1, Filter::BoundingBox);
         SVGFilterBuilder builder(dummyFilter->getSourceGraphic());
-        builder.buildGraph(dummyFilter.get(), toSVGFilterElement(*filter->element()), dummyRect);
+        builder.buildGraph(dummyFilter, toSVGFilterElement(*filter->element()), dummyRect);
         if (FilterEffect* lastEffect = builder.lastEffect())
             lastEffect->externalRepresentation(ts, indent + 1);
     } else if (resource->resourceType() == ClipperResourceType) {
diff --git a/third_party/WebKit/Source/core/layout/svg/SVGTextLayoutEngineSpacing.cpp b/third_party/WebKit/Source/core/layout/svg/SVGTextLayoutEngineSpacing.cpp
index 80aa8af..0de6f32 100644
--- a/third_party/WebKit/Source/core/layout/svg/SVGTextLayoutEngineSpacing.cpp
+++ b/third_party/WebKit/Source/core/layout/svg/SVGTextLayoutEngineSpacing.cpp
@@ -19,8 +19,8 @@
 
 #include "core/layout/svg/SVGTextLayoutEngineSpacing.h"
 
-#include "platform/fonts/Character.h"
 #include "platform/fonts/Font.h"
+#include "platform/text/Character.h"
 
 namespace blink {
 
diff --git a/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.cpp b/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.cpp
index 59c23f5..2e82f63 100644
--- a/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.cpp
+++ b/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.cpp
@@ -39,7 +39,6 @@
 #include "core/fetch/ResourceFetcher.h"
 #include "core/frame/FrameConsole.h"
 #include "core/frame/LocalFrame.h"
-#include "core/frame/csp/ContentSecurityPolicy.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/inspector/InspectorTraceEvents.h"
 #include "core/loader/CrossOriginPreflightResultCache.h"
@@ -441,7 +440,7 @@
         return;
     }
 
-    if (m_redirectMode == WebURLRequest::FetchRedirectModeError || !isAllowedByContentSecurityPolicy(request.url(), ContentSecurityPolicy::DidRedirect)) {
+    if (m_redirectMode == WebURLRequest::FetchRedirectModeError) {
         ThreadableLoaderClient* client = m_client;
         clear();
         client->didFailRedirectCheck();
@@ -529,6 +528,15 @@
     request = ResourceRequest();
 }
 
+void DocumentThreadableLoader::redirectBlocked()
+{
+    // Tells the client that a redirect was received but not followed (for an unknown reason).
+    ThreadableLoaderClient* client = m_client;
+    clear();
+    client->didFailRedirectCheck();
+    // |this| may be dead here
+}
+
 void DocumentThreadableLoader::dataSent(Resource* resource, unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
 {
     ASSERT(m_client);
@@ -881,7 +889,7 @@
     // FIXME: A synchronous request does not tell us whether a redirect happened or not, so we guess by comparing the
     // request and response URLs. This isn't a perfect test though, since a server can serve a redirect to the same URL that was
     // requested. Also comparing the request and response URLs as strings will fail if the requestURL still has its credentials.
-    if (requestURL != response.url() && (!isAllowedByContentSecurityPolicy(response.url(), ContentSecurityPolicy::DidRedirect) || !isAllowedRedirect(response.url()))) {
+    if (requestURL != response.url() && !isAllowedRedirect(response.url())) {
         m_client->didFailRedirectCheck();
         return;
     }
@@ -916,14 +924,6 @@
     return m_sameOriginRequest && getSecurityOrigin()->canRequest(url);
 }
 
-bool DocumentThreadableLoader::isAllowedByContentSecurityPolicy(const KURL& url, ContentSecurityPolicy::RedirectStatus redirectStatus) const
-{
-    if (m_options.contentSecurityPolicyEnforcement != EnforceContentSecurityPolicy)
-        return true;
-
-    return document().contentSecurityPolicy()->allowRequest(m_requestContext, url, redirectStatus);
-}
-
 StoredCredentials DocumentThreadableLoader::effectiveAllowCredentials() const
 {
     if (m_forceDoNotAllowStoredCredentials)
diff --git a/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.h b/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.h
index 91cf942..e0eda8e 100644
--- a/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.h
+++ b/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.h
@@ -35,7 +35,6 @@
 #include "core/CoreExport.h"
 #include "core/fetch/RawResource.h"
 #include "core/fetch/ResourceOwner.h"
-#include "core/frame/csp/ContentSecurityPolicy.h"
 #include "core/loader/ThreadableLoader.h"
 #include "platform/Timer.h"
 #include "platform/heap/Handle.h"
@@ -76,13 +75,6 @@
             LoadAsynchronously
         };
 
-        enum EnforceContentSecurityPolicyDirective {
-            EnforceWorkerDirective,
-            EnforceConnectSrcDirective,
-            EnforceManifestSrcDirective,
-            EnforceMediaSrcDirective,
-        };
-
         DocumentThreadableLoader(Document&, ThreadableLoaderClient*, BlockingBehavior, const ThreadableLoaderOptions&, const ResourceLoaderOptions&);
 
         void clear();
@@ -102,6 +94,7 @@
         void setSerializedCachedMetadata(Resource*, const char*, size_t) override;
         void dataReceived(Resource*, const char* data, size_t dataLength) override;
         void redirectReceived(Resource*, ResourceRequest&, const ResourceResponse&) override;
+        void redirectBlocked() override;
         void dataDownloaded(Resource*, int) override;
         void didReceiveResourceTiming(Resource*, const ResourceTimingInfo&) override;
 
@@ -151,7 +144,6 @@
 
         void loadRequest(const ResourceRequest&, ResourceLoaderOptions);
         bool isAllowedRedirect(const KURL&) const;
-        bool isAllowedByContentSecurityPolicy(const KURL&, ContentSecurityPolicy::RedirectStatus) const;
         // Returns DoNotAllowStoredCredentials
         // if m_forceDoNotAllowStoredCredentials is set. Otherwise, just
         // returns allowCredentials value of m_resourceLoaderOptions.
@@ -208,7 +200,7 @@
 
         const bool m_async;
 
-        // Holds the original request context (used for sanity checks and Content Security Policy enforcement).
+        // Holds the original request context (used for sanity checks).
         WebURLRequest::RequestContext m_requestContext;
 
         // Holds the original request for fallback in case the Service Worker
diff --git a/third_party/WebKit/Source/core/loader/EmptyClients.cpp b/third_party/WebKit/Source/core/loader/EmptyClients.cpp
index 28c292d1f..a805760 100644
--- a/third_party/WebKit/Source/core/loader/EmptyClients.cpp
+++ b/third_party/WebKit/Source/core/loader/EmptyClients.cpp
@@ -86,17 +86,17 @@
     return Platform::current()->currentThread()->getWebTaskRunner();
 }
 
-RawPtr<PopupMenu> EmptyChromeClient::openPopupMenu(LocalFrame&, HTMLSelectElement&)
+PopupMenu* EmptyChromeClient::openPopupMenu(LocalFrame&, HTMLSelectElement&)
 {
     return new EmptyPopupMenu();
 }
 
-RawPtr<ColorChooser> EmptyChromeClient::openColorChooser(LocalFrame*, ColorChooserClient*, const Color&)
+ColorChooser* EmptyChromeClient::openColorChooser(LocalFrame*, ColorChooserClient*, const Color&)
 {
     return nullptr;
 }
 
-RawPtr<DateTimeChooser> EmptyChromeClient::openDateTimeChooser(DateTimeChooserClient*, const DateTimeChooserParameters&)
+DateTimeChooser* EmptyChromeClient::openDateTimeChooser(DateTimeChooserClient*, const DateTimeChooserParameters&)
 {
     return nullptr;
 }
diff --git a/third_party/WebKit/Source/core/loader/EmptyClients.h b/third_party/WebKit/Source/core/loader/EmptyClients.h
index f347ebb..7e63973 100644
--- a/third_party/WebKit/Source/core/loader/EmptyClients.h
+++ b/third_party/WebKit/Source/core/loader/EmptyClients.h
@@ -119,7 +119,7 @@
     bool openJavaScriptPromptDelegate(LocalFrame*, const String&, const String&, String&) override { return false; }
 
     bool hasOpenedPopup() const override { return false; }
-    RawPtr<PopupMenu> openPopupMenu(LocalFrame&, HTMLSelectElement&) override;
+    PopupMenu* openPopupMenu(LocalFrame&, HTMLSelectElement&) override;
     DOMWindow* pagePopupWindowForTesting() const override { return nullptr; }
 
     void setStatusbarText(const String&) override {}
@@ -144,8 +144,8 @@
 
     void enumerateChosenDirectory(FileChooser*) override {}
 
-    RawPtr<ColorChooser> openColorChooser(LocalFrame*, ColorChooserClient*, const Color&) override;
-    RawPtr<DateTimeChooser> openDateTimeChooser(DateTimeChooserClient*, const DateTimeChooserParameters&) override;
+    ColorChooser* openColorChooser(LocalFrame*, ColorChooserClient*, const Color&) override;
+    DateTimeChooser* openDateTimeChooser(DateTimeChooserClient*, const DateTimeChooserParameters&) override;
     void openTextDataListChooser(HTMLInputElement&) override;
 
     void openFileChooser(LocalFrame*, PassRefPtr<FileChooser>) override;
diff --git a/third_party/WebKit/Source/core/loader/FrameFetchContext.cpp b/third_party/WebKit/Source/core/loader/FrameFetchContext.cpp
index fa07761..6891747b 100644
--- a/third_party/WebKit/Source/core/loader/FrameFetchContext.cpp
+++ b/third_party/WebKit/Source/core/loader/FrameFetchContext.cpp
@@ -484,69 +484,24 @@
     // I believe it's the Resource::Raw case.
     const ContentSecurityPolicy* csp = m_document ? m_document->contentSecurityPolicy() : nullptr;
 
-    // TODO(mkwst): This would be cleaner if moved this switch into an allowFromSource()
-    // helper on this object which took a Resource::Type, then this block would
-    // collapse to about 10 lines for handling Raw and Script special cases.
-    switch (type) {
-    case Resource::XSLStyleSheet:
-        ASSERT(RuntimeEnabledFeatures::xsltEnabled());
-        ASSERT(ContentSecurityPolicy::isScriptResource(resourceRequest));
-        ASSERT(csp);
-        if (!shouldBypassMainWorldCSP && !csp->allowScriptFromSource(url, redirectStatus, cspReporting))
+    if (csp) {
+        if (!shouldBypassMainWorldCSP && !csp->allowRequest(resourceRequest.requestContext(), url, redirectStatus, cspReporting))
             return ResourceRequestBlockedReasonCSP;
-        break;
-    case Resource::Script:
-    case Resource::ImportResource:
-        ASSERT(ContentSecurityPolicy::isScriptResource(resourceRequest));
-        ASSERT(csp);
-        if (!shouldBypassMainWorldCSP && !csp->allowScriptFromSource(url, redirectStatus, cspReporting))
-            return ResourceRequestBlockedReasonCSP;
+    }
+
+    if (type == Resource::Script || type == Resource::ImportResource) {
         ASSERT(frame());
         if (!frame()->loader().client()->allowScriptFromSource(!frame()->settings() || frame()->settings()->scriptEnabled(), url)) {
             frame()->loader().client()->didNotAllowScript();
+            // TODO(estark): Use a different ResourceRequestBlockedReason
+            // here, since this check has nothing to do with
+            // CSP. https://crbug.com/600795
             return ResourceRequestBlockedReasonCSP;
         }
-        break;
-    case Resource::CSSStyleSheet:
-        ASSERT(ContentSecurityPolicy::isStyleResource(resourceRequest));
-        ASSERT(csp);
-        if (!shouldBypassMainWorldCSP && !csp->allowStyleFromSource(url, redirectStatus, cspReporting))
-            return ResourceRequestBlockedReasonCSP;
-        break;
-    case Resource::SVGDocument:
-    case Resource::Image:
-        ASSERT(ContentSecurityPolicy::isImageResource(resourceRequest));
-        ASSERT(csp);
-        if (!shouldBypassMainWorldCSP && !csp->allowImageFromSource(url, redirectStatus, cspReporting))
-            return ResourceRequestBlockedReasonCSP;
-        break;
-    case Resource::Font: {
-        ASSERT(ContentSecurityPolicy::isFontResource(resourceRequest));
-        ASSERT(csp);
-        if (!shouldBypassMainWorldCSP && !csp->allowFontFromSource(url, redirectStatus, cspReporting))
-            return ResourceRequestBlockedReasonCSP;
-        break;
-    }
-    case Resource::LinkPreload:
-        ASSERT(csp);
-        if (!shouldBypassMainWorldCSP && !csp->allowConnectToSource(url, redirectStatus, cspReporting))
-            return ResourceRequestBlockedReasonCSP;
-        break;
-    case Resource::MainResource:
-    case Resource::Raw:
-    case Resource::LinkPrefetch:
-    case Resource::Manifest:
-        break;
-    case Resource::Media:
-    case Resource::TextTrack:
-        ASSERT(ContentSecurityPolicy::isMediaResource(resourceRequest));
-        ASSERT(csp);
-        if (!shouldBypassMainWorldCSP && !csp->allowMediaFromSource(url, redirectStatus, cspReporting))
-            return ResourceRequestBlockedReasonCSP;
-
+    } else if (type == Resource::Media || type == Resource::TextTrack) {
+        ASSERT(frame());
         if (!frame()->loader().client()->allowMedia(url))
             return ResourceRequestBlockedReasonOther;
-        break;
     }
 
     // SVG Images have unique security rules that prevent all subresource requests
@@ -554,13 +509,6 @@
     if (type != Resource::MainResource && frame()->chromeClient().isSVGImageChromeClient() && !url.protocolIsData())
         return ResourceRequestBlockedReasonOrigin;
 
-    // FIXME: Once we use RequestContext for CSP (http://crbug.com/390497), remove this extra check.
-    if (resourceRequest.requestContext() == WebURLRequest::RequestContextManifest) {
-        ASSERT(csp);
-        if (!shouldBypassMainWorldCSP && !csp->allowManifestFromSource(url, redirectStatus, cspReporting))
-            return ResourceRequestBlockedReasonCSP;
-    }
-
     // Measure the number of legacy URL schemes ('ftp://') and the number of embedded-credential
     // ('http://user:password@...') resources embedded as subresources. in the hopes that we can
     // block them at some point in the future.
diff --git a/third_party/WebKit/Source/core/loader/TextTrackLoader.cpp b/third_party/WebKit/Source/core/loader/TextTrackLoader.cpp
index 190a623d..db966ba 100644
--- a/third_party/WebKit/Source/core/loader/TextTrackLoader.cpp
+++ b/third_party/WebKit/Source/core/loader/TextTrackLoader.cpp
@@ -168,6 +168,7 @@
     visitor->trace(m_cueParser);
     visitor->trace(m_document);
     ResourceOwner<RawResource>::trace(visitor);
+    VTTParserClient::trace(visitor);
 }
 
 } // namespace blink
diff --git a/third_party/WebKit/Source/core/page/AutoscrollController.cpp b/third_party/WebKit/Source/core/page/AutoscrollController.cpp
index ce0c222..bc3d77ae 100644
--- a/third_party/WebKit/Source/core/page/AutoscrollController.cpp
+++ b/third_party/WebKit/Source/core/page/AutoscrollController.cpp
@@ -43,7 +43,7 @@
 // Delay time in second for start autoscroll if pointer is in border edge of scrollable element.
 static double autoscrollDelay = 0.2;
 
-RawPtr<AutoscrollController> AutoscrollController::create(Page& page)
+AutoscrollController* AutoscrollController::create(Page& page)
 {
     return new AutoscrollController(page);
 }
diff --git a/third_party/WebKit/Source/core/page/AutoscrollController.h b/third_party/WebKit/Source/core/page/AutoscrollController.h
index 1f4f8a27..794a460 100644
--- a/third_party/WebKit/Source/core/page/AutoscrollController.h
+++ b/third_party/WebKit/Source/core/page/AutoscrollController.h
@@ -54,7 +54,7 @@
 // AutscrollController handels autoscroll and pan scroll for EventHandler.
 class CORE_EXPORT AutoscrollController final : public GarbageCollected<AutoscrollController> {
 public:
-    static RawPtr<AutoscrollController> create(Page&);
+    static AutoscrollController* create(Page&);
     DECLARE_TRACE();
 
     static const int noPanScrollRadius = 15;
diff --git a/third_party/WebKit/Source/core/page/ChromeClient.h b/third_party/WebKit/Source/core/page/ChromeClient.h
index 5b6d6de..3057804 100644
--- a/third_party/WebKit/Source/core/page/ChromeClient.h
+++ b/third_party/WebKit/Source/core/page/ChromeClient.h
@@ -161,7 +161,7 @@
 
     virtual void annotatedRegionsChanged() = 0;
 
-    virtual RawPtr<ColorChooser> openColorChooser(LocalFrame*, ColorChooserClient*, const Color&) = 0;
+    virtual ColorChooser* openColorChooser(LocalFrame*, ColorChooserClient*, const Color&) = 0;
 
     // This function is used for:
     //  - Mandatory date/time choosers if !ENABLE(INPUT_MULTIPLE_FIELDS_UI)
@@ -169,7 +169,7 @@
     //    returns true, if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
     //  - <datalist> UI for date/time input types regardless of
     //    ENABLE(INPUT_MULTIPLE_FIELDS_UI)
-    virtual RawPtr<DateTimeChooser> openDateTimeChooser(DateTimeChooserClient*, const DateTimeChooserParameters&) = 0;
+    virtual DateTimeChooser* openDateTimeChooser(DateTimeChooserClient*, const DateTimeChooserParameters&) = 0;
 
     virtual void openTextDataListChooser(HTMLInputElement&)= 0;
 
@@ -205,7 +205,7 @@
 
     // Checks if there is an opened popup, called by LayoutMenuList::showPopup().
     virtual bool hasOpenedPopup() const = 0;
-    virtual RawPtr<PopupMenu> openPopupMenu(LocalFrame&, HTMLSelectElement&) = 0;
+    virtual PopupMenu* openPopupMenu(LocalFrame&, HTMLSelectElement&) = 0;
     virtual DOMWindow* pagePopupWindowForTesting() const = 0;
 
     virtual void postAccessibilityNotification(AXObject*, AXObjectCache::AXNotification) { }
diff --git a/third_party/WebKit/Source/core/page/ChromeClientTest.cpp b/third_party/WebKit/Source/core/page/ChromeClientTest.cpp
index c8829ff..b830ba8 100644
--- a/third_party/WebKit/Source/core/page/ChromeClientTest.cpp
+++ b/third_party/WebKit/Source/core/page/ChromeClientTest.cpp
@@ -37,10 +37,10 @@
     ChromeClientToolTipLogger logger;
     ChromeClient* client = &logger;
     HitTestResult result(HitTestRequest(HitTestRequest::Move), LayoutPoint(10, 20));
-    RawPtr<Document> doc = Document::create();
-    RawPtr<Element> element = HTMLElement::create(HTMLNames::divTag, *doc);
+    Document* doc = Document::create();
+    Element* element = HTMLElement::create(HTMLNames::divTag, *doc);
     element->setAttribute(HTMLNames::titleAttr, "tooltip");
-    result.setInnerNode(element.get());
+    result.setInnerNode(element);
 
     client->setToolTip(result);
     EXPECT_EQ("tooltip", logger.toolTipForLastSetToolTip());
diff --git a/third_party/WebKit/Source/core/page/ContextMenuControllerTest.cpp b/third_party/WebKit/Source/core/page/ContextMenuControllerTest.cpp
index c45e878..f6270fd0 100644
--- a/third_party/WebKit/Source/core/page/ContextMenuControllerTest.cpp
+++ b/third_party/WebKit/Source/core/page/ContextMenuControllerTest.cpp
@@ -68,12 +68,12 @@
         "</button>");
 
     // Create right button click event and pass it to context menu controller.
-    RawPtr<Event> event = MouseEvent::create(EventTypeNames::click, false, false,
+    Event* event = MouseEvent::create(EventTypeNames::click, false, false,
         document().domWindow(), 50, 50, 0, 0, 0, 0, 0, PlatformEvent::NoModifiers, 1, 0, nullptr, 0,
         PlatformMouseEvent::RealOrIndistinguishable, String());
     document().getElementById("button_id")->focus();
     event->setTarget(document().getElementById("button_id"));
-    document().page()->contextMenuController().handleContextMenuEvent(event.get());
+    document().page()->contextMenuController().handleContextMenuEvent(event);
 
     // Item 1
     // Item 2
diff --git a/third_party/WebKit/Source/core/page/CustomContextMenuProvider.cpp b/third_party/WebKit/Source/core/page/CustomContextMenuProvider.cpp
index 3b52812..6410a73 100644
--- a/third_party/WebKit/Source/core/page/CustomContextMenuProvider.cpp
+++ b/third_party/WebKit/Source/core/page/CustomContextMenuProvider.cpp
@@ -44,9 +44,9 @@
 void CustomContextMenuProvider::contextMenuItemSelected(const ContextMenuItem* item)
 {
     if (HTMLElement* element = menuItemAt(item->action())) {
-        RawPtr<MouseEvent> click = MouseEvent::create(EventTypeNames::click, m_menu->document().domWindow(), Event::create(), SimulatedClickCreationScope::FromUserAgent);
+        MouseEvent* click = MouseEvent::create(EventTypeNames::click, m_menu->document().domWindow(), Event::create(), SimulatedClickCreationScope::FromUserAgent);
         click->setRelatedTarget(m_subjectElement.get());
-        element->dispatchEvent(click.release());
+        element->dispatchEvent(click);
     }
 }
 
diff --git a/third_party/WebKit/Source/core/page/CustomContextMenuProvider.h b/third_party/WebKit/Source/core/page/CustomContextMenuProvider.h
index 0bcc180..f2b10c1 100644
--- a/third_party/WebKit/Source/core/page/CustomContextMenuProvider.h
+++ b/third_party/WebKit/Source/core/page/CustomContextMenuProvider.h
@@ -20,7 +20,7 @@
 public:
     ~CustomContextMenuProvider() override;
 
-    static RawPtr<CustomContextMenuProvider> create(HTMLMenuElement& menu, HTMLElement& subject)
+    static CustomContextMenuProvider* create(HTMLMenuElement& menu, HTMLElement& subject)
     {
         return new CustomContextMenuProvider(menu, subject);
     }
diff --git a/third_party/WebKit/Source/core/page/DragController.cpp b/third_party/WebKit/Source/core/page/DragController.cpp
index 69f9d72..970ac8ce 100644
--- a/third_party/WebKit/Source/core/page/DragController.cpp
+++ b/third_party/WebKit/Source/core/page/DragController.cpp
@@ -141,26 +141,26 @@
 {
 }
 
-RawPtr<DragController> DragController::create(Page* page, DragClient* client)
+DragController* DragController::create(Page* page, DragClient* client)
 {
     return new DragController(page, client);
 }
 
-static RawPtr<DocumentFragment> documentFragmentFromDragData(DragData* dragData, LocalFrame* frame, RawPtr<Range> context, bool allowPlainText, bool& chosePlainText)
+static DocumentFragment* documentFragmentFromDragData(DragData* dragData, LocalFrame* frame, Range* context, bool allowPlainText, bool& chosePlainText)
 {
     ASSERT(dragData);
     chosePlainText = false;
 
     Document& document = context->ownerDocument();
     if (dragData->containsCompatibleContent()) {
-        if (RawPtr<DocumentFragment> fragment = dragData->asFragment(frame))
+        if (DocumentFragment* fragment = dragData->asFragment(frame))
             return fragment;
 
         if (dragData->containsURL(DragData::DoNotConvertFilenames)) {
             String title;
             String url = dragData->asURL(DragData::DoNotConvertFilenames, &title);
             if (!url.isEmpty()) {
-                RawPtr<HTMLAnchorElement> anchor = HTMLAnchorElement::create(document);
+                HTMLAnchorElement* anchor = HTMLAnchorElement::create(document);
                 anchor->setHref(AtomicString(url));
                 if (title.isEmpty()) {
                     // Try the plain text first because the url might be normalized or escaped.
@@ -169,17 +169,17 @@
                     if (title.isEmpty())
                         title = url;
                 }
-                RawPtr<Node> anchorText = document.createTextNode(title);
+                Node* anchorText = document.createTextNode(title);
                 anchor->appendChild(anchorText);
-                RawPtr<DocumentFragment> fragment = document.createDocumentFragment();
+                DocumentFragment* fragment = document.createDocumentFragment();
                 fragment->appendChild(anchor);
-                return fragment.release();
+                return fragment;
             }
         }
     }
     if (allowPlainText && dragData->containsPlainText()) {
         chosePlainText = true;
-        return createFragmentFromText(EphemeralRange(context.get()), dragData->asPlainText()).get();
+        return createFragmentFromText(EphemeralRange(context), dragData->asPlainText()).get();
     }
 
     return nullptr;
@@ -213,7 +213,7 @@
     ASSERT(dragData);
     LocalFrame* mainFrame = m_page->deprecatedLocalMainFrame();
 
-    RawPtr<FrameView> frameView(mainFrame->view());
+    FrameView* frameView(mainFrame->view());
     if (frameView) {
         DataTransferAccessPolicy policy = (!m_documentUnderMouse || m_documentUnderMouse->getSecurityOrigin()->isLocal()) ? DataTransferReadable : DataTransferTypesReadable;
         DataTransfer* dataTransfer = createDraggingDataTransfer(policy, dragData);
@@ -237,7 +237,7 @@
     ASSERT(dragData);
     m_documentUnderMouse = m_page->deprecatedLocalMainFrame()->documentAtPoint(dragData->clientPosition());
     if ((m_dragDestinationAction & DragDestinationActionDHTML) && m_documentIsHandlingDrag) {
-        RawPtr<LocalFrame> mainFrame = m_page->deprecatedLocalMainFrame();
+        LocalFrame* mainFrame = m_page->deprecatedLocalMainFrame();
         bool preventedDefault = false;
         if (mainFrame->view()) {
             // Sending an event can result in the destruction of the view and part.
@@ -356,7 +356,7 @@
 
     // It's unclear why this check is after tryDHTMLDrag.
     // We send drag events in tryDHTMLDrag and that may be the reason.
-    RawPtr<FrameView> frameView = m_documentUnderMouse->view();
+    FrameView* frameView = m_documentUnderMouse->view();
     if (!frameView)
         return false;
 
@@ -429,7 +429,7 @@
     return dragOperation(dragData);
 }
 
-static bool setSelectionToDragCaret(LocalFrame* frame, VisibleSelection& dragCaret, RawPtr<Range>& range, const IntPoint& point)
+static bool setSelectionToDragCaret(LocalFrame* frame, VisibleSelection& dragCaret, Range*& range, const IntPoint& point)
 {
     frame->selection().setSelection(dragCaret);
     if (frame->selection().isNone()) {
@@ -452,7 +452,7 @@
 {
     ASSERT(dragData);
 
-    RawPtr<HTMLInputElement> fileInput = m_fileInputElementUnderMouse;
+    HTMLInputElement* fileInput = m_fileInputElementUnderMouse;
     if (m_fileInputElementUnderMouse) {
         m_fileInputElementUnderMouse->setCanReceiveDroppedFiles(false);
         m_fileInputElementUnderMouse = nullptr;
@@ -465,10 +465,10 @@
     Element* element = elementUnderMouse(m_documentUnderMouse.get(), point);
     if (!element)
         return false;
-    RawPtr<LocalFrame> innerFrame = element->ownerDocument()->frame();
+    LocalFrame* innerFrame = element->ownerDocument()->frame();
     ASSERT(innerFrame);
 
-    if (m_page->dragCaretController().hasCaret() && dispatchTextInputEventFor(innerFrame.get(), dragData) != DispatchEventResult::NotCanceled)
+    if (m_page->dragCaretController().hasCaret() && dispatchTextInputEventFor(innerFrame, dragData) != DispatchEventResult::NotCanceled)
         return true;
 
     if (dragData->containsFiles() && fileInput) {
@@ -488,8 +488,8 @@
 
     VisibleSelection dragCaret(m_page->dragCaretController().caretPosition());
     m_page->dragCaretController().clear();
-    RawPtr<Range> range = createRange(dragCaret.toNormalizedEphemeralRange());
-    RawPtr<Element> rootEditableElement = innerFrame->selection().rootEditableElement();
+    Range* range = createRange(dragCaret.toNormalizedEphemeralRange());
+    Element* rootEditableElement = innerFrame->selection().rootEditableElement();
 
     // For range to be null a WebKit client must have done something bad while
     // manually controlling drag behaviour
@@ -499,7 +499,7 @@
     ResourceCacheValidationSuppressor validationSuppressor(fetcher);
     if (dragIsMove(innerFrame->selection(), dragData) || dragCaret.isContentRichlyEditable()) {
         bool chosePlainText = false;
-        RawPtr<DocumentFragment> fragment = documentFragmentFromDragData(dragData, innerFrame.get(), range, true, chosePlainText);
+        DocumentFragment* fragment = documentFragmentFromDragData(dragData, innerFrame, range, true, chosePlainText);
         if (!fragment)
             return false;
 
@@ -510,7 +510,7 @@
             bool smartInsert = smartDelete && innerFrame->selection().granularity() == WordGranularity && dragData->canSmartReplace();
             innerFrame->editor().moveSelectionAfterDragging(fragment, dragCaret.base(), smartInsert, smartDelete);
         } else {
-            if (setSelectionToDragCaret(innerFrame.get(), dragCaret, range, point)) {
+            if (setSelectionToDragCaret(innerFrame, dragCaret, range, point)) {
                 ASSERT(m_documentUnderMouse);
                 m_documentUnderMouse->frame()->editor().replaceSelectionAfterDragging(fragment, dragData->canSmartReplace(), chosePlainText);
             }
@@ -520,17 +520,17 @@
         if (text.isEmpty())
             return false;
 
-        if (setSelectionToDragCaret(innerFrame.get(), dragCaret, range, point)) {
+        if (setSelectionToDragCaret(innerFrame, dragCaret, range, point)) {
             const bool canSmartReplace = false;
             const bool chosePlainText = true;
             ASSERT(m_documentUnderMouse);
-            m_documentUnderMouse->frame()->editor().replaceSelectionAfterDragging(createFragmentFromText(EphemeralRange(range.get()), text), canSmartReplace, chosePlainText);
+            m_documentUnderMouse->frame()->editor().replaceSelectionAfterDragging(createFragmentFromText(EphemeralRange(range), text), canSmartReplace, chosePlainText);
         }
     }
 
     if (rootEditableElement) {
         if (LocalFrame* frame = rootEditableElement->document().frame())
-            frame->eventHandler().updateDragStateAfterEditDragIfNeeded(rootEditableElement.get());
+            frame->eventHandler().updateDragStateAfterEditDragIfNeeded(rootEditableElement);
     }
 
     return true;
@@ -592,11 +592,10 @@
 {
     ASSERT(dragData);
     ASSERT(m_documentUnderMouse);
-    RawPtr<LocalFrame> mainFrame = m_page->deprecatedLocalMainFrame();
+    LocalFrame* mainFrame = m_page->deprecatedLocalMainFrame();
     if (!mainFrame->view())
         return false;
 
-    RawPtr<FrameView> viewProtector(mainFrame->view());
     DataTransferAccessPolicy policy = m_documentUnderMouse->getSecurityOrigin()->isLocal() ? DataTransferReadable : DataTransferTypesReadable;
     DataTransfer* dataTransfer = createDraggingDataTransfer(policy, dragData);
     DragOperation srcOpMask = dragData->draggingSourceOperationMask();
@@ -713,9 +712,9 @@
 static void prepareDataTransferForImageDrag(LocalFrame* source, DataTransfer* dataTransfer, Element* node, const KURL& linkURL, const KURL& imageURL, const String& label)
 {
     if (node->isContentRichlyEditable()) {
-        RawPtr<Range> range = source->document()->createRange();
+        Range* range = source->document()->createRange();
         range->selectNode(node, ASSERT_NO_EXCEPTION);
-        source->selection().setSelection(VisibleSelection(EphemeralRange(range.get())));
+        source->selection().setSelection(VisibleSelection(EphemeralRange(range)));
     }
     dataTransfer->declareAndWriteDragImage(node, !linkURL.isEmpty() ? linkURL : imageURL, label);
 }
@@ -730,7 +729,7 @@
     HitTestResult hitTestResult = src->eventHandler().hitTestResultAtPoint(dragOrigin);
     // FIXME: Can this even happen? I guess it's possible, but should verify
     // with a layout test.
-    if (!state.m_dragSrc->containsIncludingShadowDOM(hitTestResult.innerNode())) {
+    if (!state.m_dragSrc->isShadowIncludingInclusiveAncestorOf(hitTestResult.innerNode())) {
         // The original node being dragged isn't under the drag origin anymore... maybe it was
         // hidden or moved out from under the cursor. Regardless, we don't want to start a drag on
         // something that's not actually under the drag origin.
@@ -853,7 +852,7 @@
         return false;
 
     HitTestResult hitTestResult = src->eventHandler().hitTestResultAtPoint(dragOrigin);
-    if (!state.m_dragSrc->containsIncludingShadowDOM(hitTestResult.innerNode())) {
+    if (!state.m_dragSrc->isShadowIncludingInclusiveAncestorOf(hitTestResult.innerNode())) {
         // The original node being dragged isn't under the drag origin anymore... maybe it was
         // hidden or moved out from under the cursor. Regardless, we don't want to start a drag on
         // something that's not actually under the drag origin.
@@ -942,8 +941,8 @@
     m_didInitiateDrag = true;
     m_dragInitiator = frame->document();
     // Protect this frame and view, as a load may occur mid drag and attempt to unload this frame
-    RawPtr<LocalFrame> mainFrame = m_page->deprecatedLocalMainFrame();
-    RawPtr<FrameView> mainFrameView = mainFrame->view();
+    LocalFrame* mainFrame = m_page->deprecatedLocalMainFrame();
+    FrameView* mainFrameView = mainFrame->view();
 
     m_client->startDrag(image, mainFrameView->rootFrameToContents(frame->view()->contentsToRootFrame(dragLocation)),
         mainFrameView->rootFrameToContents(frame->view()->contentsToRootFrame(eventPos)), dataTransfer, frame, forLink);
diff --git a/third_party/WebKit/Source/core/page/DragController.h b/third_party/WebKit/Source/core/page/DragController.h
index 0d72194..e318b19 100644
--- a/third_party/WebKit/Source/core/page/DragController.h
+++ b/third_party/WebKit/Source/core/page/DragController.h
@@ -55,7 +55,7 @@
 public:
     ~DragController();
 
-    static RawPtr<DragController> create(Page*, DragClient*);
+    static DragController* create(Page*, DragClient*);
 
     DragSession dragEntered(DragData*);
     void dragExited(DragData*);
diff --git a/third_party/WebKit/Source/core/page/DragData.cpp b/third_party/WebKit/Source/core/page/DragData.cpp
index 78d2b363..2294f03a 100644
--- a/third_party/WebKit/Source/core/page/DragData.cpp
+++ b/third_party/WebKit/Source/core/page/DragData.cpp
@@ -116,7 +116,7 @@
         || containsFiles();
 }
 
-RawPtr<DocumentFragment> DragData::asFragment(LocalFrame* frame) const
+DocumentFragment* DragData::asFragment(LocalFrame* frame) const
 {
     /*
      * Order is richest format first. On OSX this is:
@@ -138,8 +138,8 @@
         KURL baseURL;
         m_platformDragData->htmlAndBaseURL(html, baseURL);
         ASSERT(frame->document());
-        if (RawPtr<DocumentFragment> fragment = createFragmentFromMarkup(*frame->document(), html, baseURL, DisallowScriptingAndPluginContent))
-            return fragment.release();
+        if (DocumentFragment* fragment = createFragmentFromMarkup(*frame->document(), html, baseURL, DisallowScriptingAndPluginContent))
+            return fragment;
     }
 
     return nullptr;
diff --git a/third_party/WebKit/Source/core/page/DragData.h b/third_party/WebKit/Source/core/page/DragData.h
index 92342e1..bf07abc 100644
--- a/third_party/WebKit/Source/core/page/DragData.h
+++ b/third_party/WebKit/Source/core/page/DragData.h
@@ -67,7 +67,7 @@
     String asURL(FilenameConversionPolicy filenamePolicy = ConvertFilenames, String* title = nullptr) const;
     String asPlainText() const;
     void asFilePaths(Vector<String>&) const;
-    RawPtr<DocumentFragment> asFragment(LocalFrame*) const;
+    DocumentFragment* asFragment(LocalFrame*) const;
     bool canSmartReplace() const;
     bool containsFiles() const;
     int modifiers() const;
diff --git a/third_party/WebKit/Source/core/page/EventSource.cpp b/third_party/WebKit/Source/core/page/EventSource.cpp
index 030739c..676c78c 100644
--- a/third_party/WebKit/Source/core/page/EventSource.cpp
+++ b/third_party/WebKit/Source/core/page/EventSource.cpp
@@ -317,7 +317,7 @@
 
 void EventSource::onMessageEvent(const AtomicString& eventType, const String& data, const AtomicString& lastEventId)
 {
-    RawPtr<MessageEvent> e = MessageEvent::create();
+    MessageEvent* e = MessageEvent::create();
     e->initMessageEvent(eventType, false, false, SerializedScriptValueFactory::instance().create(data), m_eventStreamOrigin, lastEventId, 0, nullptr);
 
     InspectorInstrumentation::willDispatchEventSourceEvent(getExecutionContext(), this, eventType, lastEventId, data);
diff --git a/third_party/WebKit/Source/core/page/FocusController.cpp b/third_party/WebKit/Source/core/page/FocusController.cpp
index e7db0e88b..d4e28bb 100644
--- a/third_party/WebKit/Source/core/page/FocusController.cpp
+++ b/third_party/WebKit/Source/core/page/FocusController.cpp
@@ -340,7 +340,7 @@
     }
 
     if (!focused && document->focusedElement()) {
-        RawPtr<Element> focusedElement(document->focusedElement());
+        Element* focusedElement = document->focusedElement();
         focusedElement->setFocus(false);
         dispatchBlurEvent(*document, *focusedElement);
     }
@@ -348,7 +348,7 @@
     if (LocalDOMWindow* window = document->domWindow())
         window->dispatchEvent(Event::create(focused ? EventTypeNames::focus : EventTypeNames::blur));
     if (focused && document->focusedElement()) {
-        RawPtr<Element> focusedElement(document->focusedElement());
+        Element* focusedElement(document->focusedElement());
         focusedElement->setFocus(true);
         dispatchFocusEvent(*document, *focusedElement);
     }
@@ -373,7 +373,7 @@
 
 inline bool isNonKeyboardFocusableShadowHost(const Element& element)
 {
-    return isShadowHostWithoutCustomFocusLogic(element) && !element.isKeyboardFocusable();
+    return isShadowHostWithoutCustomFocusLogic(element) && !(element.shadowRootIfV1() ? element.isFocusable() : element.isKeyboardFocusable());
 }
 
 inline bool isKeyboardFocusableShadowHost(const Element& element)
@@ -721,12 +721,12 @@
 {
 }
 
-RawPtr<FocusController> FocusController::create(Page* page)
+FocusController* FocusController::create(Page* page)
 {
     return new FocusController(page);
 }
 
-void FocusController::setFocusedFrame(RawPtr<Frame> frame, bool notifyEmbedder)
+void FocusController::setFocusedFrame(Frame* frame, bool notifyEmbedder)
 {
     ASSERT(!frame || frame->page() == m_page);
     if (m_focusedFrame == frame || (m_isChangingFocusedFrame && frame))
@@ -734,11 +734,11 @@
 
     m_isChangingFocusedFrame = true;
 
-    RawPtr<LocalFrame> oldFrame = (m_focusedFrame && m_focusedFrame->isLocalFrame()) ? toLocalFrame(m_focusedFrame.get()) : nullptr;
+    LocalFrame* oldFrame = (m_focusedFrame && m_focusedFrame->isLocalFrame()) ? toLocalFrame(m_focusedFrame.get()) : nullptr;
 
-    RawPtr<LocalFrame> newFrame = (frame && frame->isLocalFrame()) ? toLocalFrame(frame.get()) : nullptr;
+    LocalFrame* newFrame = (frame && frame->isLocalFrame()) ? toLocalFrame(frame) : nullptr;
 
-    m_focusedFrame = frame.get();
+    m_focusedFrame = frame;
 
     // Now that the frame is updated, fire events and update the selection focused states of both frames.
     if (oldFrame && oldFrame->view()) {
@@ -759,23 +759,23 @@
         m_focusedFrame->client()->frameFocused();
 }
 
-void FocusController::focusDocumentView(RawPtr<Frame> frame, bool notifyEmbedder)
+void FocusController::focusDocumentView(Frame* frame, bool notifyEmbedder)
 {
     ASSERT(!frame || frame->page() == m_page);
     if (m_focusedFrame == frame)
         return;
 
-    RawPtr<LocalFrame> focusedFrame = (m_focusedFrame && m_focusedFrame->isLocalFrame()) ? toLocalFrame(m_focusedFrame.get()) : nullptr;
+    LocalFrame* focusedFrame = (m_focusedFrame && m_focusedFrame->isLocalFrame()) ? toLocalFrame(m_focusedFrame.get()) : nullptr;
     if (focusedFrame && focusedFrame->view()) {
-        RawPtr<Document> document = focusedFrame->document();
+        Document* document = focusedFrame->document();
         Element* focusedElement = document ? document->focusedElement() : nullptr;
         if (focusedElement)
             dispatchBlurEvent(*document, *focusedElement);
     }
 
-    RawPtr<LocalFrame> newFocusedFrame = (frame && frame->isLocalFrame()) ? toLocalFrame(frame.get()) : nullptr;
+    LocalFrame* newFocusedFrame = (frame && frame->isLocalFrame()) ? toLocalFrame(frame) : nullptr;
     if (newFocusedFrame && newFocusedFrame->view()) {
-        RawPtr<Document> document = newFocusedFrame->document();
+        Document* document = newFocusedFrame->document();
         Element* focusedElement = document ? document->focusedElement() : nullptr;
         if (focusedElement)
             dispatchFocusEvent(*document, *focusedElement);
@@ -923,7 +923,7 @@
 
     document->updateLayoutIgnorePendingStylesheets();
     ScopedFocusNavigation scope = current ? ScopedFocusNavigation::createFor(*current) : ScopedFocusNavigation::createForDocument(*document);
-    RawPtr<Element> element = findFocusableElementAcrossFocusScopes(type, scope);
+    Element* element = findFocusableElementAcrossFocusScopes(type, scope);
     if (!element) {
         // If there's a RemoteFrame on the ancestor chain, we need to continue
         // searching for focusable elements there.
@@ -946,7 +946,7 @@
         // Chrome doesn't want focus, so we should wrap focus.
         ScopedFocusNavigation scope = ScopedFocusNavigation::createForDocument(*toLocalFrame(m_page->mainFrame())->document());
         element = findFocusableElementRecursively(type, scope);
-        element = findFocusableElementDescendingDownIntoFrameDocument(type, element.get());
+        element = findFocusableElementDescendingDownIntoFrameDocument(type, element);
 
         if (!element)
             return false;
@@ -992,7 +992,7 @@
     setFocusedFrame(newDocument.frame());
 
     if (caretBrowsing) {
-        Position position = firstPositionInOrBeforeNode(element.get());
+        Position position = firstPositionInOrBeforeNode(element);
         VisibleSelection newSelection(position, position);
         frame->selection().setSelection(newSelection);
     }
@@ -1051,15 +1051,15 @@
     selection.clear();
 }
 
-bool FocusController::setFocusedElement(Element* element, RawPtr<Frame> newFocusedFrame)
+bool FocusController::setFocusedElement(Element* element, Frame* newFocusedFrame)
 {
     return setFocusedElement(element, newFocusedFrame, FocusParams(SelectionBehaviorOnFocus::None, WebFocusTypeNone, nullptr));
 }
 
-bool FocusController::setFocusedElement(Element* element, RawPtr<Frame> newFocusedFrame, const FocusParams& params)
+bool FocusController::setFocusedElement(Element* element, Frame* newFocusedFrame, const FocusParams& params)
 {
-    RawPtr<LocalFrame> oldFocusedFrame = focusedFrame();
-    RawPtr<Document> oldDocument = oldFocusedFrame ? oldFocusedFrame->document() : nullptr;
+    LocalFrame* oldFocusedFrame = focusedFrame();
+    Document* oldDocument = oldFocusedFrame ? oldFocusedFrame->document() : nullptr;
 
     Element* oldFocusedElement = oldDocument ? oldDocument->focusedElement() : nullptr;
     if (element && oldFocusedElement == element)
@@ -1071,17 +1071,17 @@
 
     m_page->chromeClient().willSetInputMethodState();
 
-    RawPtr<Document> newDocument = nullptr;
+    Document* newDocument = nullptr;
     if (element)
         newDocument = &element->document();
     else if (newFocusedFrame && newFocusedFrame->isLocalFrame())
-        newDocument = toLocalFrame(newFocusedFrame.get())->document();
+        newDocument = toLocalFrame(newFocusedFrame)->document();
 
     if (newDocument && oldDocument == newDocument && newDocument->focusedElement() == element)
         return true;
 
     if (newFocusedFrame && newFocusedFrame->isLocalFrame())
-        clearSelectionIfNeeded(oldFocusedFrame.get(), toLocalFrame(newFocusedFrame.get()), element);
+        clearSelectionIfNeeded(oldFocusedFrame, toLocalFrame(newFocusedFrame), element);
 
     if (oldDocument && oldDocument != newDocument)
         oldDocument->clearFocusedElement();
@@ -1092,9 +1092,6 @@
     }
     setFocusedFrame(newFocusedFrame);
 
-    // Setting the focused element can result in losing our last reft to element when JS event handlers fire.
-    RawPtr<Element> protect = element;
-    ALLOW_UNUSED_LOCAL(protect);
     if (newDocument) {
         bool successfullyFocused = newDocument->setFocusedElement(element, params);
         if (!successfullyFocused)
diff --git a/third_party/WebKit/Source/core/page/FocusController.h b/third_party/WebKit/Source/core/page/FocusController.h
index c4c2370f..97bf4c54 100644
--- a/third_party/WebKit/Source/core/page/FocusController.h
+++ b/third_party/WebKit/Source/core/page/FocusController.h
@@ -51,10 +51,10 @@
 class CORE_EXPORT FocusController final : public GarbageCollectedFinalized<FocusController> {
     WTF_MAKE_NONCOPYABLE(FocusController);
 public:
-    static RawPtr<FocusController> create(Page*);
+    static FocusController* create(Page*);
 
-    void setFocusedFrame(RawPtr<Frame>, bool notifyEmbedder = true);
-    void focusDocumentView(RawPtr<Frame>, bool notifyEmbedder = true);
+    void setFocusedFrame(Frame*, bool notifyEmbedder = true);
+    void focusDocumentView(Frame*, bool notifyEmbedder = true);
     LocalFrame* focusedFrame() const;
     Frame* focusedOrMainFrame() const;
 
@@ -72,10 +72,10 @@
     bool advanceFocusAcrossFrames(WebFocusType, RemoteFrame* from, LocalFrame* to, InputDeviceCapabilities* sourceCapabilities = nullptr);
     Element* findFocusableElementInShadowHost(const Element& shadowHost);
 
-    bool setFocusedElement(Element*, RawPtr<Frame>, const FocusParams&);
+    bool setFocusedElement(Element*, Frame*, const FocusParams&);
     // |setFocusedElement| variant with SelectionBehaviorOnFocus::None,
     // |WebFocusTypeNone, and null InputDeviceCapabilities.
-    bool setFocusedElement(Element*, RawPtr<Frame>);
+    bool setFocusedElement(Element*, Frame*);
 
     void setActive(bool);
     bool isActive() const { return m_isActive; }
diff --git a/third_party/WebKit/Source/core/page/Page.cpp b/third_party/WebKit/Source/core/page/Page.cpp
index fd79db8..d6d6a86 100644
--- a/third_party/WebKit/Source/core/page/Page.cpp
+++ b/third_party/WebKit/Source/core/page/Page.cpp
@@ -106,12 +106,12 @@
     return page->deviceScaleFactor();
 }
 
-RawPtr<Page> Page::createOrdinary(PageClients& pageClients)
+Page* Page::createOrdinary(PageClients& pageClients)
 {
-    RawPtr<Page> page = create(pageClients);
-    ordinaryPages().add(page.get());
-    page->memoryPurgeController().registerClient(page.get());
-    return page.release();
+    Page* page = create(pageClients);
+    ordinaryPages().add(page);
+    page->memoryPurgeController().registerClient(page);
+    return page;
 }
 
 Page::Page(PageClients& pageClients)
@@ -282,7 +282,7 @@
     } while (frame);
 }
 
-void Page::setValidationMessageClient(RawPtr<ValidationMessageClient> client)
+void Page::setValidationMessageClient(ValidationMessageClient* client)
 {
     m_validationMessageClient = client;
 }
@@ -545,7 +545,7 @@
 
 void Page::willBeDestroyed()
 {
-    RawPtr<Frame> mainFrame = m_mainFrame;
+    Frame* mainFrame = m_mainFrame;
 
     mainFrame->detach(FrameDetachType::Remove);
 
diff --git a/third_party/WebKit/Source/core/page/Page.h b/third_party/WebKit/Source/core/page/Page.h
index 13ef51e..0c4e1a01 100644
--- a/third_party/WebKit/Source/core/page/Page.h
+++ b/third_party/WebKit/Source/core/page/Page.h
@@ -92,13 +92,13 @@
         SpellCheckerClient* spellCheckerClient;
     };
 
-    static RawPtr<Page> create(PageClients& pageClients)
+    static Page* create(PageClients& pageClients)
     {
         return new Page(pageClients);
     }
 
     // An "ordinary" page is a fully-featured page owned by a web view.
-    static RawPtr<Page> createOrdinary(PageClients&);
+    static Page* createOrdinary(PageClients&);
 
     ~Page() override;
 
@@ -153,7 +153,7 @@
     ContextMenuController& contextMenuController() const { return *m_contextMenuController; }
     PointerLockController& pointerLockController() const { return *m_pointerLockController; }
     ValidationMessageClient& validationMessageClient() const { return *m_validationMessageClient; }
-    void setValidationMessageClient(RawPtr<ValidationMessageClient>);
+    void setValidationMessageClient(ValidationMessageClient*);
 
     ScrollingCoordinator* scrollingCoordinator();
 
diff --git a/third_party/WebKit/Source/core/page/PageAnimator.cpp b/third_party/WebKit/Source/core/page/PageAnimator.cpp
index 8db25c2..6309656f 100644
--- a/third_party/WebKit/Source/core/page/PageAnimator.cpp
+++ b/third_party/WebKit/Source/core/page/PageAnimator.cpp
@@ -21,7 +21,7 @@
 {
 }
 
-RawPtr<PageAnimator> PageAnimator::create(Page& page)
+PageAnimator* PageAnimator::create(Page& page)
 {
     return new PageAnimator(page);
 }
@@ -33,7 +33,6 @@
 
 void PageAnimator::serviceScriptedAnimations(double monotonicAnimationStartTime)
 {
-    RawPtr<PageAnimator> protector(this);
     TemporaryChange<bool> servicing(m_servicingAnimations, true);
     clock().updateTime(monotonicAnimationStartTime);
 
@@ -80,7 +79,7 @@
 
 void PageAnimator::updateAllLifecyclePhases(LocalFrame& rootFrame)
 {
-    RawPtr<FrameView> view = rootFrame.view();
+    FrameView* view = rootFrame.view();
     TemporaryChange<bool> servicing(m_updatingLayoutAndStyleForPainting, true);
     view->updateAllLifecyclePhases();
 }
diff --git a/third_party/WebKit/Source/core/page/PageAnimator.h b/third_party/WebKit/Source/core/page/PageAnimator.h
index eb318a4b..cdfc39d2 100644
--- a/third_party/WebKit/Source/core/page/PageAnimator.h
+++ b/third_party/WebKit/Source/core/page/PageAnimator.h
@@ -16,7 +16,7 @@
 
 class CORE_EXPORT PageAnimator final : public GarbageCollected<PageAnimator> {
 public:
-    static RawPtr<PageAnimator> create(Page&);
+    static PageAnimator* create(Page&);
     DECLARE_TRACE();
     void scheduleVisualUpdate(LocalFrame*);
     void serviceScriptedAnimations(double monotonicAnimationStartTime);
diff --git a/third_party/WebKit/Source/core/page/PagePopupController.cpp b/third_party/WebKit/Source/core/page/PagePopupController.cpp
index f713c9bb..344c58b 100644
--- a/third_party/WebKit/Source/core/page/PagePopupController.cpp
+++ b/third_party/WebKit/Source/core/page/PagePopupController.cpp
@@ -44,7 +44,7 @@
     ASSERT(client);
 }
 
-RawPtr<PagePopupController> PagePopupController::create(PagePopup& popup, PagePopupClient* client)
+PagePopupController* PagePopupController::create(PagePopup& popup, PagePopupClient* client)
 {
     return new PagePopupController(popup, client);
 }
diff --git a/third_party/WebKit/Source/core/page/PagePopupController.h b/third_party/WebKit/Source/core/page/PagePopupController.h
index b6964d6..56484aca 100644
--- a/third_party/WebKit/Source/core/page/PagePopupController.h
+++ b/third_party/WebKit/Source/core/page/PagePopupController.h
@@ -45,7 +45,7 @@
 class PagePopupController final : public GarbageCollected<PagePopupController>, public ScriptWrappable {
     DEFINE_WRAPPERTYPEINFO();
 public:
-    static RawPtr<PagePopupController> create(PagePopup&, PagePopupClient*);
+    static PagePopupController* create(PagePopup&, PagePopupClient*);
     void setValueAndClosePopup(int numValue, const String& stringValue);
     void setValue(const String&);
     void closePopup();
diff --git a/third_party/WebKit/Source/core/page/PointerLockController.cpp b/third_party/WebKit/Source/core/page/PointerLockController.cpp
index 89ef59b..c5b6dbc 100644
--- a/third_party/WebKit/Source/core/page/PointerLockController.cpp
+++ b/third_party/WebKit/Source/core/page/PointerLockController.cpp
@@ -40,14 +40,14 @@
 {
 }
 
-RawPtr<PointerLockController> PointerLockController::create(Page* page)
+PointerLockController* PointerLockController::create(Page* page)
 {
     return new PointerLockController(page);
 }
 
 void PointerLockController::requestPointerLock(Element* target)
 {
-    if (!target || !target->inDocument() || m_documentOfRemovedElementWhileWaitingForUnlock) {
+    if (!target || !target->inShadowIncludingDocument() || m_documentOfRemovedElementWhileWaitingForUnlock) {
         enqueueEvent(EventTypeNames::pointerlockerror, target);
         return;
     }
diff --git a/third_party/WebKit/Source/core/page/PointerLockController.h b/third_party/WebKit/Source/core/page/PointerLockController.h
index 4ad00ed..306a434 100644
--- a/third_party/WebKit/Source/core/page/PointerLockController.h
+++ b/third_party/WebKit/Source/core/page/PointerLockController.h
@@ -40,7 +40,7 @@
 class CORE_EXPORT PointerLockController final : public GarbageCollected<PointerLockController> {
     WTF_MAKE_NONCOPYABLE(PointerLockController);
 public:
-    static RawPtr<PointerLockController> create(Page*);
+    static PointerLockController* create(Page*);
 
     void requestPointerLock(Element* target);
     void requestPointerUnlock();
diff --git a/third_party/WebKit/Source/core/page/PrintContext.cpp b/third_party/WebKit/Source/core/page/PrintContext.cpp
index 69010082..e608c390 100644
--- a/third_party/WebKit/Source/core/page/PrintContext.cpp
+++ b/third_party/WebKit/Source/core/page/PrintContext.cpp
@@ -187,8 +187,6 @@
 
 int PrintContext::pageNumberForElement(Element* element, const FloatSize& pageSizeInPixels)
 {
-    // Make sure the element is not freed during the layout.
-    RawPtr<Element> protect(element);
     element->document().updateLayout();
 
     LayoutBoxModelObject* box = enclosingBoxModelObject(element->layoutObject());
diff --git a/third_party/WebKit/Source/core/page/PrintContextTest.cpp b/third_party/WebKit/Source/core/page/PrintContextTest.cpp
index f09539d2..922a629 100644
--- a/third_party/WebKit/Source/core/page/PrintContextTest.cpp
+++ b/third_party/WebKit/Source/core/page/PrintContextTest.cpp
@@ -71,7 +71,7 @@
 
 class PrintContextTest : public RenderingTest {
 protected:
-    explicit PrintContextTest(RawPtr<FrameLoaderClient> frameLoaderClient = nullptr)
+    explicit PrintContextTest(FrameLoaderClient* frameLoaderClient = nullptr)
         : RenderingTest(frameLoaderClient) { }
 
     void SetUp() override
diff --git a/third_party/WebKit/Source/core/page/scrolling/ScrollState.cpp b/third_party/WebKit/Source/core/page/scrolling/ScrollState.cpp
index 67f114f..c9c2221 100644
--- a/third_party/WebKit/Source/core/page/scrolling/ScrollState.cpp
+++ b/third_party/WebKit/Source/core/page/scrolling/ScrollState.cpp
@@ -24,7 +24,7 @@
 }
 } // namespace
 
-RawPtr<ScrollState> ScrollState::create(ScrollStateInit init)
+ScrollState* ScrollState::create(ScrollStateInit init)
 {
     OwnPtr<ScrollStateData> scrollStateData = adoptPtr(new ScrollStateData());
     scrollStateData->delta_x = init.deltaX();
@@ -44,7 +44,7 @@
     return scrollState;
 }
 
-RawPtr<ScrollState> ScrollState::create(PassOwnPtr<ScrollStateData> data)
+ScrollState* ScrollState::create(PassOwnPtr<ScrollStateData> data)
 {
     ScrollState* scrollState = new ScrollState(data);
     return scrollState;
diff --git a/third_party/WebKit/Source/core/page/scrolling/ScrollState.h b/third_party/WebKit/Source/core/page/scrolling/ScrollState.h
index 8b371db..4a37781 100644
--- a/third_party/WebKit/Source/core/page/scrolling/ScrollState.h
+++ b/third_party/WebKit/Source/core/page/scrolling/ScrollState.h
@@ -19,8 +19,8 @@
     DEFINE_WRAPPERTYPEINFO();
 
 public:
-    static RawPtr<ScrollState> create(ScrollStateInit);
-    static RawPtr<ScrollState> create(PassOwnPtr<ScrollStateData>);
+    static ScrollState* create(ScrollStateInit);
+    static ScrollState* create(PassOwnPtr<ScrollStateData>);
 
     ~ScrollState()
     {
diff --git a/third_party/WebKit/Source/core/page/scrolling/ScrollStateTest.cpp b/third_party/WebKit/Source/core/page/scrolling/ScrollStateTest.cpp
index 76d7b771..c8b9858 100644
--- a/third_party/WebKit/Source/core/page/scrolling/ScrollStateTest.cpp
+++ b/third_party/WebKit/Source/core/page/scrolling/ScrollStateTest.cpp
@@ -12,7 +12,7 @@
 
 namespace {
 
-RawPtr<ScrollState> CreateScrollState(double deltaX, double deltaY, bool beginning, bool ending)
+ScrollState* CreateScrollState(double deltaX, double deltaY, bool beginning, bool ending)
 {
     OwnPtr<ScrollStateData> scrollStateData = adoptPtr(new ScrollStateData());
     scrollStateData->delta_x = deltaX;
@@ -33,7 +33,7 @@
     const float deltaXToConsume = 1.2;
     const float deltaYToConsume = 2.3;
 
-    RawPtr<ScrollState> scrollState = CreateScrollState(deltaX, deltaY, false, false);
+    ScrollState* scrollState = CreateScrollState(deltaX, deltaY, false, false);
     EXPECT_FLOAT_EQ(deltaX, scrollState->deltaX());
     EXPECT_FLOAT_EQ(deltaY, scrollState->deltaY());
     EXPECT_FALSE(scrollState->deltaConsumedForScrollSequence());
@@ -64,19 +64,19 @@
 
 TEST_F(ScrollStateTest, CurrentNativeScrollingElement)
 {
-    RawPtr<ScrollState> scrollState = CreateScrollState(0, 0, false, false);
-    RawPtr<Element> element = Element::create(
+    ScrollState* scrollState = CreateScrollState(0, 0, false, false);
+    Element* element = Element::create(
         QualifiedName::null(), Document::create().get());
-    scrollState->setCurrentNativeScrollingElement(element.get());
+    scrollState->setCurrentNativeScrollingElement(element);
 
     EXPECT_EQ(element, scrollState->currentNativeScrollingElement());
 }
 
 TEST_F(ScrollStateTest, FullyConsumed)
 {
-    RawPtr<ScrollState> scrollStateBegin = CreateScrollState(0, 0, true, false);
-    RawPtr<ScrollState> scrollState = CreateScrollState(0, 0, false, false);
-    RawPtr<ScrollState> scrollStateEnd = CreateScrollState(0, 0, false, true);
+    ScrollState* scrollStateBegin = CreateScrollState(0, 0, true, false);
+    ScrollState* scrollState = CreateScrollState(0, 0, false, false);
+    ScrollState* scrollStateEnd = CreateScrollState(0, 0, false, true);
     EXPECT_FALSE(scrollStateBegin->fullyConsumed());
     EXPECT_TRUE(scrollState->fullyConsumed());
     EXPECT_FALSE(scrollStateEnd->fullyConsumed());
diff --git a/third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinator.cpp b/third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinator.cpp
index e15eb53..2597121 100644
--- a/third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinator.cpp
+++ b/third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinator.cpp
@@ -82,7 +82,7 @@
 
 namespace blink {
 
-RawPtr<ScrollingCoordinator> ScrollingCoordinator::create(Page* page)
+ScrollingCoordinator* ScrollingCoordinator::create(Page* page)
 {
     return new ScrollingCoordinator(page);
 }
@@ -797,7 +797,7 @@
     for (const auto& eventTarget : *targets) {
         EventTarget* target = eventTarget.key;
         Node* node = target->toNode();
-        if (!node || !node->inDocument())
+        if (!node || !node->inShadowIncludingDocument())
             continue;
 
         // If the document belongs to an invisible subframe it does not have a composited layer
diff --git a/third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinator.h b/third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinator.h
index 44aba89..f503f8f7 100644
--- a/third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinator.h
+++ b/third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinator.h
@@ -55,7 +55,7 @@
 class CORE_EXPORT ScrollingCoordinator final : public GarbageCollectedFinalized<ScrollingCoordinator> {
     WTF_MAKE_NONCOPYABLE(ScrollingCoordinator);
 public:
-    static RawPtr<ScrollingCoordinator> create(Page*);
+    static ScrollingCoordinator* create(Page*);
 
     ~ScrollingCoordinator();
     DECLARE_TRACE();
diff --git a/third_party/WebKit/Source/core/svg/SVGAnimateElement.cpp b/third_party/WebKit/Source/core/svg/SVGAnimateElement.cpp
index 331c461..4dac59a 100644
--- a/third_party/WebKit/Source/core/svg/SVGAnimateElement.cpp
+++ b/third_party/WebKit/Source/core/svg/SVGAnimateElement.cpp
@@ -233,7 +233,7 @@
 static inline void applyCSSPropertyToTargetAndInstances(SVGElement* targetElement, const QualifiedName& attributeName, const String& valueAsString)
 {
     ASSERT(targetElement);
-    if (attributeName == anyQName() || !targetElement->inDocument() || !targetElement->parentNode())
+    if (attributeName == anyQName() || !targetElement->inShadowIncludingDocument() || !targetElement->parentNode())
         return;
 
     CSSPropertyID id = cssPropertyID(attributeName.localName());
@@ -252,7 +252,7 @@
 static inline void removeCSSPropertyFromTargetAndInstances(SVGElement* targetElement, const QualifiedName& attributeName)
 {
     ASSERT(targetElement);
-    if (attributeName == anyQName() || !targetElement->inDocument() || !targetElement->parentNode())
+    if (attributeName == anyQName() || !targetElement->inShadowIncludingDocument() || !targetElement->parentNode())
         return;
 
     CSSPropertyID id = cssPropertyID(attributeName.localName());
@@ -280,7 +280,7 @@
 static inline void notifyTargetAndInstancesAboutAnimValChange(SVGElement* targetElement, const QualifiedName& attributeName)
 {
     ASSERT(targetElement);
-    if (attributeName == anyQName() || !targetElement->inDocument() || !targetElement->parentNode())
+    if (attributeName == anyQName() || !targetElement->inShadowIncludingDocument() || !targetElement->parentNode())
         return;
 
     SVGElement::InstanceUpdateBlocker blocker(targetElement);
diff --git a/third_party/WebKit/Source/core/svg/SVGDocumentExtensions.cpp b/third_party/WebKit/Source/core/svg/SVGDocumentExtensions.cpp
index d4f7ef5..cb607ff 100644
--- a/third_party/WebKit/Source/core/svg/SVGDocumentExtensions.cpp
+++ b/third_party/WebKit/Source/core/svg/SVGDocumentExtensions.cpp
@@ -156,7 +156,7 @@
 void SVGDocumentExtensions::addPendingResource(const AtomicString& id, Element* element)
 {
     ASSERT(element);
-    ASSERT(element->inDocument());
+    ASSERT(element->inShadowIncludingDocument());
 
     if (id.isEmpty())
         return;
diff --git a/third_party/WebKit/Source/core/svg/SVGElement.cpp b/third_party/WebKit/Source/core/svg/SVGElement.cpp
index 54255cd5..430a794 100644
--- a/third_party/WebKit/Source/core/svg/SVGElement.cpp
+++ b/third_party/WebKit/Source/core/svg/SVGElement.cpp
@@ -73,7 +73,7 @@
 
 SVGElement::~SVGElement()
 {
-    ASSERT(inDocument() || !hasRelativeLengths());
+    ASSERT(inShadowIncludingDocument() || !hasRelativeLengths());
 
     // The below teardown is all handled by weak pointer processing in oilpan.
 #if !ENABLE(OILPAN)
@@ -125,7 +125,7 @@
 void SVGElement::buildPendingResourcesIfNeeded()
 {
     Document& document = this->document();
-    if (!needsPendingResourceHandling() || !inDocument() || inUseShadowTree())
+    if (!needsPendingResourceHandling() || !inShadowIncludingDocument() || inUseShadowTree())
         return;
 
     SVGDocumentExtensions& extensions = document.accessSVGExtensions();
@@ -301,7 +301,7 @@
 
 void SVGElement::removedFrom(ContainerNode* rootParent)
 {
-    bool wasInDocument = rootParent->inDocument();
+    bool wasInDocument = rootParent->inShadowIncludingDocument();
 
     if (wasInDocument && hasRelativeLengths()) {
         // The root of the subtree being removed should take itself out from its parent's relative
@@ -420,7 +420,7 @@
     ASSERT(clientElement);
 
     // If we're not yet in a document, this function will be called again from insertedInto(). Do nothing now.
-    if (!inDocument())
+    if (!inShadowIncludingDocument())
         return;
 
     // An element wants to notify us that its own relative lengths state changed.
@@ -456,7 +456,7 @@
 
 void SVGElement::invalidateRelativeLengthClients(SubtreeLayoutScope* layoutScope)
 {
-    if (!inDocument())
+    if (!inShadowIncludingDocument())
         return;
 
     ASSERT(!m_inRelativeLengthClientsInvalidation);
@@ -885,7 +885,7 @@
         // Notify resources about id changes, this is important as we cache resources by id in SVGDocumentExtensions
         if (object && object->isSVGResourceContainer())
             toLayoutSVGResourceContainer(object)->idChanged();
-        if (inDocument())
+        if (inShadowIncludingDocument())
             buildPendingResourcesIfNeeded();
         invalidateInstances();
         return;
@@ -1012,7 +1012,7 @@
         instance->setCorrespondingElement(0);
 
         if (SVGUseElement* element = instance->correspondingUseElement()) {
-            if (element->inDocument())
+            if (element->inShadowIncludingDocument())
                 element->invalidateShadowTree();
         }
     }
diff --git a/third_party/WebKit/Source/core/svg/SVGFEImageElement.cpp b/third_party/WebKit/Source/core/svg/SVGFEImageElement.cpp
index e581146..c1d7bd8 100644
--- a/third_party/WebKit/Source/core/svg/SVGFEImageElement.cpp
+++ b/third_party/WebKit/Source/core/svg/SVGFEImageElement.cpp
@@ -91,7 +91,7 @@
 void SVGFEImageElement::buildPendingResource()
 {
     clearResourceReferences();
-    if (!inDocument())
+    if (!inShadowIncludingDocument())
         return;
 
     AtomicString id;
@@ -139,13 +139,13 @@
 void SVGFEImageElement::removedFrom(ContainerNode* rootParent)
 {
     SVGFilterPrimitiveStandardAttributes::removedFrom(rootParent);
-    if (rootParent->inDocument())
+    if (rootParent->inShadowIncludingDocument())
         clearResourceReferences();
 }
 
 void SVGFEImageElement::notifyFinished(Resource*)
 {
-    if (!inDocument())
+    if (!inShadowIncludingDocument())
         return;
 
     Element* parent = parentElement();
diff --git a/third_party/WebKit/Source/core/svg/SVGImageElement.cpp b/third_party/WebKit/Source/core/svg/SVGImageElement.cpp
index 15976d9..8bd5312 100644
--- a/third_party/WebKit/Source/core/svg/SVGImageElement.cpp
+++ b/third_party/WebKit/Source/core/svg/SVGImageElement.cpp
@@ -134,7 +134,7 @@
 
     if (SVGURIReference::isKnownAttribute(attrName)) {
         SVGElement::InvalidationGuard invalidationGuard(this);
-        if (inDocument())
+        if (inShadowIncludingDocument())
             imageLoader().updateFromElement(ImageLoader::UpdateIgnorePreviousError);
         else
             m_needsLoaderURIUpdate = true;
@@ -177,7 +177,7 @@
 Node::InsertionNotificationRequest SVGImageElement::insertedInto(ContainerNode* rootParent)
 {
     SVGGraphicsElement::insertedInto(rootParent);
-    if (!rootParent->inDocument())
+    if (!rootParent->inShadowIncludingDocument())
         return InsertionDone;
 
     // We can only resolve base URIs properly after tree insertion - hence, URI mutations while
diff --git a/third_party/WebKit/Source/core/svg/SVGLengthTearOff.cpp b/third_party/WebKit/Source/core/svg/SVGLengthTearOff.cpp
index 06d0e83..2e0ecdaa 100644
--- a/third_party/WebKit/Source/core/svg/SVGLengthTearOff.cpp
+++ b/third_party/WebKit/Source/core/svg/SVGLengthTearOff.cpp
@@ -59,7 +59,7 @@
 
 inline bool canResolveRelativeUnits(const SVGElement* contextElement)
 {
-    return contextElement && contextElement->inDocument();
+    return contextElement && contextElement->inShadowIncludingDocument();
 }
 
 inline CSSPrimitiveValue::UnitType toCSSUnitType(unsigned short type)
diff --git a/third_party/WebKit/Source/core/svg/SVGMPathElement.cpp b/third_party/WebKit/Source/core/svg/SVGMPathElement.cpp
index 8ff94fd..f576b5aa 100644
--- a/third_party/WebKit/Source/core/svg/SVGMPathElement.cpp
+++ b/third_party/WebKit/Source/core/svg/SVGMPathElement.cpp
@@ -51,7 +51,7 @@
 void SVGMPathElement::buildPendingResource()
 {
     clearResourceReferences();
-    if (!inDocument())
+    if (!inShadowIncludingDocument())
         return;
 
     AtomicString id;
@@ -82,7 +82,7 @@
 Node::InsertionNotificationRequest SVGMPathElement::insertedInto(ContainerNode* rootParent)
 {
     SVGElement::insertedInto(rootParent);
-    if (rootParent->inDocument())
+    if (rootParent->inShadowIncludingDocument())
         buildPendingResource();
     return InsertionDone;
 }
@@ -91,7 +91,7 @@
 {
     SVGElement::removedFrom(rootParent);
     notifyParentOfPathChange(rootParent);
-    if (rootParent->inDocument())
+    if (rootParent->inShadowIncludingDocument())
         clearResourceReferences();
 }
 
diff --git a/third_party/WebKit/Source/core/svg/SVGSVGElement.cpp b/third_party/WebKit/Source/core/svg/SVGSVGElement.cpp
index 3b4703bb..baec216 100644
--- a/third_party/WebKit/Source/core/svg/SVGSVGElement.cpp
+++ b/third_party/WebKit/Source/core/svg/SVGSVGElement.cpp
@@ -96,7 +96,7 @@
     // is dead as well and there is no reason to clear the extensions.
     document().accessSVGExtensions().removeTimeContainer(this);
 
-    ASSERT(inDocument() || !accessDocumentSVGExtensions().isSVGRootWithRelativeLengthDescendents(this));
+    ASSERT(inShadowIncludingDocument() || !accessDocumentSVGExtensions().isSVGRootWithRelativeLengthDescendents(this));
 #endif
 }
 
@@ -116,7 +116,7 @@
 
 float SVGSVGElement::currentScale() const
 {
-    if (!inDocument() || !isOutermostSVGSVGElement())
+    if (!inShadowIncludingDocument() || !isOutermostSVGSVGElement())
         return 1;
 
     return m_currentScale;
@@ -125,7 +125,7 @@
 void SVGSVGElement::setCurrentScale(float scale)
 {
     ASSERT(std::isfinite(scale));
-    if (!inDocument() || !isOutermostSVGSVGElement())
+    if (!inShadowIncludingDocument() || !isOutermostSVGSVGElement())
         return;
 
     m_currentScale = scale;
@@ -507,7 +507,7 @@
 
 Node::InsertionNotificationRequest SVGSVGElement::insertedInto(ContainerNode* rootParent)
 {
-    if (rootParent->inDocument()) {
+    if (rootParent->inShadowIncludingDocument()) {
         UseCounter::count(document(), UseCounter::SVGSVGElementInDocument);
         if (rootParent->document().isXMLDocument())
             UseCounter::count(document(), UseCounter::SVGSVGElementInXMLDocument);
@@ -527,7 +527,7 @@
 
 void SVGSVGElement::removedFrom(ContainerNode* rootParent)
 {
-    if (rootParent->inDocument()) {
+    if (rootParent->inShadowIncludingDocument()) {
         SVGDocumentExtensions& svgExtensions = document().accessSVGExtensions();
         svgExtensions.removeTimeContainer(this);
         svgExtensions.removeSVGRootWithRelativeLengthDescendents(this);
diff --git a/third_party/WebKit/Source/core/svg/SVGTextPathElement.cpp b/third_party/WebKit/Source/core/svg/SVGTextPathElement.cpp
index 8cb6cb5..7f6063e 100644
--- a/third_party/WebKit/Source/core/svg/SVGTextPathElement.cpp
+++ b/third_party/WebKit/Source/core/svg/SVGTextPathElement.cpp
@@ -120,7 +120,7 @@
 void SVGTextPathElement::buildPendingResource()
 {
     clearResourceReferences();
-    if (!inDocument())
+    if (!inShadowIncludingDocument())
         return;
 
     AtomicString id;
@@ -154,7 +154,7 @@
 void SVGTextPathElement::removedFrom(ContainerNode* rootParent)
 {
     SVGTextContentElement::removedFrom(rootParent);
-    if (rootParent->inDocument())
+    if (rootParent->inShadowIncludingDocument())
         clearResourceReferences();
 }
 
diff --git a/third_party/WebKit/Source/core/svg/SVGTitleElement.cpp b/third_party/WebKit/Source/core/svg/SVGTitleElement.cpp
index 98eaae9..f825bd4f 100644
--- a/third_party/WebKit/Source/core/svg/SVGTitleElement.cpp
+++ b/third_party/WebKit/Source/core/svg/SVGTitleElement.cpp
@@ -38,7 +38,7 @@
 Node::InsertionNotificationRequest SVGTitleElement::insertedInto(ContainerNode* rootParent)
 {
     SVGElement::insertedInto(rootParent);
-    if (!rootParent->inDocument())
+    if (!rootParent->inShadowIncludingDocument())
         return InsertionDone;
     if (hasChildren() && document().isSVGDocument())
         document().setTitleElement(this);
@@ -48,14 +48,14 @@
 void SVGTitleElement::removedFrom(ContainerNode* rootParent)
 {
     SVGElement::removedFrom(rootParent);
-    if (rootParent->inDocument() && document().isSVGDocument())
+    if (rootParent->inShadowIncludingDocument() && document().isSVGDocument())
         document().removeTitle(this);
 }
 
 void SVGTitleElement::childrenChanged(const ChildrenChange& change)
 {
     SVGElement::childrenChanged(change);
-    if (inDocument() && document().isSVGDocument() && !m_ignoreTitleUpdatesWhenChildrenChange)
+    if (inShadowIncludingDocument() && document().isSVGDocument() && !m_ignoreTitleUpdatesWhenChildrenChange)
         document().setTitleElement(this);
 }
 
diff --git a/third_party/WebKit/Source/core/svg/SVGUseElement.cpp b/third_party/WebKit/Source/core/svg/SVGUseElement.cpp
index dc8abfc2..ee7b856 100644
--- a/third_party/WebKit/Source/core/svg/SVGUseElement.cpp
+++ b/third_party/WebKit/Source/core/svg/SVGUseElement.cpp
@@ -122,7 +122,7 @@
 {
     // This functions exists to assure assumptions made in the code regarding SVGElementInstance creation/destruction are satisfied.
     SVGGraphicsElement::insertedInto(rootParent);
-    if (!rootParent->inDocument())
+    if (!rootParent->inShadowIncludingDocument())
         return InsertionDone;
     ASSERT(!m_targetElementInstance || !isWellFormedDocument(&document()));
     ASSERT(!hasPendingResources() || !isWellFormedDocument(&document()));
@@ -133,7 +133,7 @@
 void SVGUseElement::removedFrom(ContainerNode* rootParent)
 {
     SVGGraphicsElement::removedFrom(rootParent);
-    if (rootParent->inDocument()) {
+    if (rootParent->inShadowIncludingDocument()) {
         clearShadowTree();
         cancelShadowTreeRecreation();
     }
@@ -320,7 +320,7 @@
         return;
     clearShadowTree();
     cancelShadowTreeRecreation();
-    if (!inDocument())
+    if (!inShadowIncludingDocument())
         return;
     Document* externalDocument = this->externalDocument();
     if (isStructurallyExternal() && !externalDocument)
@@ -328,7 +328,7 @@
 
     AtomicString id;
     Element* target = targetElementFromIRIString(hrefString(), treeScope(), &id, externalDocument);
-    if (!target || !target->inDocument()) {
+    if (!target || !target->inShadowIncludingDocument()) {
         // If we can't find the target of an external element, just give up.
         // We can't observe if the target somewhen enters the external document, nor should we do it.
         if (externalDocument)
@@ -369,7 +369,7 @@
 // case).
 static inline void removeDisallowedElementsFromSubtree(SVGElement& subtree)
 {
-    ASSERT(!subtree.inDocument());
+    ASSERT(!subtree.inShadowIncludingDocument());
     Element* element = ElementTraversal::firstWithin(subtree);
     while (element) {
         if (isDisallowedElement(*element)) {
@@ -652,7 +652,7 @@
     instances.appendRange(rawInstances.begin(), rawInstances.end());
     for (auto& instance : instances) {
         if (SVGUseElement* element = instance->correspondingUseElement()) {
-            ASSERT(element->inDocument());
+            ASSERT(element->inShadowIncludingDocument());
             element->invalidateShadowTree();
         }
     }
@@ -705,7 +705,7 @@
 void SVGUseElement::notifyFinished(Resource* resource)
 {
     ASSERT(m_resource == resource);
-    if (!inDocument())
+    if (!inShadowIncludingDocument())
         return;
 
     invalidateShadowTree();
diff --git a/third_party/WebKit/Source/core/svg/animation/SMILTimeContainer.cpp b/third_party/WebKit/Source/core/svg/animation/SMILTimeContainer.cpp
index f6d9521..66685621 100644
--- a/third_party/WebKit/Source/core/svg/animation/SMILTimeContainer.cpp
+++ b/third_party/WebKit/Source/core/svg/animation/SMILTimeContainer.cpp
@@ -532,17 +532,17 @@
 #endif
 
     for (unsigned i = 0; i < animationsToApplySize; ++i) {
-        if (animationsToApply[i]->inDocument() && animationsToApply[i]->isSVGDiscardElement()) {
+        if (animationsToApply[i]->inShadowIncludingDocument() && animationsToApply[i]->isSVGDiscardElement()) {
             SVGSMILElement* animDiscard = animationsToApply[i];
             SVGElement* targetElement = animDiscard->targetElement();
-            if (targetElement && targetElement->inDocument()) {
+            if (targetElement && targetElement->inShadowIncludingDocument()) {
                 targetElement->remove(IGNORE_EXCEPTION);
-                ASSERT(!targetElement->inDocument());
+                ASSERT(!targetElement->inShadowIncludingDocument());
             }
 
-            if (animDiscard->inDocument()) {
+            if (animDiscard->inShadowIncludingDocument()) {
                 animDiscard->remove(IGNORE_EXCEPTION);
-                ASSERT(!animDiscard->inDocument());
+                ASSERT(!animDiscard->inShadowIncludingDocument());
             }
         }
     }
diff --git a/third_party/WebKit/Source/core/svg/animation/SVGSMILElement.cpp b/third_party/WebKit/Source/core/svg/animation/SVGSMILElement.cpp
index f8e05d5d..f3d5977 100644
--- a/third_party/WebKit/Source/core/svg/animation/SVGSMILElement.cpp
+++ b/third_party/WebKit/Source/core/svg/animation/SVGSMILElement.cpp
@@ -232,7 +232,7 @@
 {
     clearResourceAndEventBaseReferences();
 
-    if (!inDocument()) {
+    if (!inShadowIncludingDocument()) {
         // Reset the target element if we are no longer in the document.
         setTargetElement(nullptr);
         return;
@@ -247,7 +247,7 @@
         target = SVGURIReference::targetElementFromIRIString(href, treeScope(), &id);
     SVGElement* svgTarget = target && target->isSVGElement() ? toSVGElement(target) : nullptr;
 
-    if (svgTarget && !svgTarget->inDocument())
+    if (svgTarget && !svgTarget->inShadowIncludingDocument())
         svgTarget = nullptr;
 
     if (svgTarget != targetElement())
@@ -323,7 +323,7 @@
 {
     SVGElement::insertedInto(rootParent);
 
-    if (!rootParent->inDocument())
+    if (!rootParent->inShadowIncludingDocument())
         return InsertionDone;
 
     Deprecation::countDeprecation(document(), UseCounter::SVGSMILElementInDocument);
@@ -354,7 +354,7 @@
 
 void SVGSMILElement::removedFrom(ContainerNode* rootParent)
 {
-    if (rootParent->inDocument()) {
+    if (rootParent->inShadowIncludingDocument()) {
         clearResourceAndEventBaseReferences();
         clearConditions();
         setTargetElement(nullptr);
@@ -527,7 +527,7 @@
             parseBeginOrEnd(fastGetAttribute(SVGNames::endAttr), End);
         }
         parseBeginOrEnd(value.getString(), Begin);
-        if (inDocument())
+        if (inShadowIncludingDocument())
             connectSyncBaseConditions();
     } else if (name == SVGNames::endAttr) {
         if (!m_conditions.isEmpty()) {
@@ -535,7 +535,7 @@
             parseBeginOrEnd(fastGetAttribute(SVGNames::beginAttr), Begin);
         }
         parseBeginOrEnd(value.getString(), End);
-        if (inDocument())
+        if (inShadowIncludingDocument())
             connectSyncBaseConditions();
     } else if (name == SVGNames::onbeginAttr) {
         setAttributeEventListener(EventTypeNames::beginEvent, createAttributeEventListener(this, name, value, eventParameterName()));
@@ -569,7 +569,7 @@
         if (m_targetElement)
             clearAnimatedType();
     } else if (attrName == SVGNames::beginAttr || attrName == SVGNames::endAttr) {
-        if (inDocument()) {
+        if (inShadowIncludingDocument()) {
             connectEventBaseConditions();
             if (attrName == SVGNames::beginAttr)
                 beginListChanged(elapsed());
diff --git a/third_party/WebKit/Source/core/testing/DummyPageHolder.cpp b/third_party/WebKit/Source/core/testing/DummyPageHolder.cpp
index 8f193712..fd3dcd8 100644
--- a/third_party/WebKit/Source/core/testing/DummyPageHolder.cpp
+++ b/third_party/WebKit/Source/core/testing/DummyPageHolder.cpp
@@ -48,7 +48,7 @@
 PassOwnPtr<DummyPageHolder> DummyPageHolder::create(
     const IntSize& initialViewSize,
     Page::PageClients* pageClients,
-    RawPtr<FrameLoaderClient> frameLoaderClient,
+    FrameLoaderClient* frameLoaderClient,
     FrameSettingOverrideFunction settingOverrider) {
     return adoptPtr(new DummyPageHolder(initialViewSize, pageClients, frameLoaderClient, settingOverrider));
 }
@@ -56,7 +56,7 @@
 DummyPageHolder::DummyPageHolder(
     const IntSize& initialViewSize,
     Page::PageClients* pageClientsArgument,
-    RawPtr<FrameLoaderClient> frameLoaderClient,
+    FrameLoaderClient* frameLoaderClient,
     FrameSettingOverrideFunction settingOverrider)
 {
     Page::PageClients pageClients;
diff --git a/third_party/WebKit/Source/core/testing/DummyPageHolder.h b/third_party/WebKit/Source/core/testing/DummyPageHolder.h
index 276604e..67257e8 100644
--- a/third_party/WebKit/Source/core/testing/DummyPageHolder.h
+++ b/third_party/WebKit/Source/core/testing/DummyPageHolder.h
@@ -68,7 +68,7 @@
     static PassOwnPtr<DummyPageHolder> create(
         const IntSize& initialViewSize = IntSize(),
         Page::PageClients* = 0,
-        RawPtr<FrameLoaderClient> = nullptr,
+        FrameLoaderClient* = nullptr,
         FrameSettingOverrideFunction = nullptr);
     ~DummyPageHolder();
 
@@ -78,7 +78,7 @@
     Document& document() const;
 
 private:
-    DummyPageHolder(const IntSize& initialViewSize, Page::PageClients*, RawPtr<FrameLoaderClient>, FrameSettingOverrideFunction settingOverrider);
+    DummyPageHolder(const IntSize& initialViewSize, Page::PageClients*, FrameLoaderClient*, FrameSettingOverrideFunction settingOverrider);
 
     Persistent<Page> m_page;
     Persistent<LocalFrame> m_frame;
diff --git a/third_party/WebKit/Source/core/testing/InternalSettings.h b/third_party/WebKit/Source/core/testing/InternalSettings.h
index 1b9e8a8..c8909e7 100644
--- a/third_party/WebKit/Source/core/testing/InternalSettings.h
+++ b/third_party/WebKit/Source/core/testing/InternalSettings.h
@@ -78,7 +78,7 @@
         bool m_originalCompositorWorkerEnabled;
     };
 
-    static RawPtr<InternalSettings> create(Page& page)
+    static InternalSettings* create(Page& page)
     {
         return new InternalSettings(page);
     }
diff --git a/third_party/WebKit/Source/core/testing/Internals.cpp b/third_party/WebKit/Source/core/testing/Internals.cpp
index a46a23e3..da1d48b4 100644
--- a/third_party/WebKit/Source/core/testing/Internals.cpp
+++ b/third_party/WebKit/Source/core/testing/Internals.cpp
@@ -657,17 +657,17 @@
     return representation;
 }
 
-RawPtr<CSSStyleDeclaration> Internals::computedStyleIncludingVisitedInfo(Node* node) const
+CSSStyleDeclaration* Internals::computedStyleIncludingVisitedInfo(Node* node) const
 {
     ASSERT(node);
     bool allowVisitedStyle = true;
     return CSSComputedStyleDeclaration::create(node, allowVisitedStyle);
 }
 
-RawPtr<ShadowRoot> Internals::createUserAgentShadowRoot(Element* host)
+ShadowRoot* Internals::createUserAgentShadowRoot(Element* host)
 {
     ASSERT(host);
-    return RawPtr<ShadowRoot>(host->ensureUserAgentShadowRoot());
+    return &host->ensureUserAgentShadowRoot();
 }
 
 ShadowRoot* Internals::shadowRoot(Element* host)
@@ -874,7 +874,7 @@
     return markers[index];
 }
 
-RawPtr<Range> Internals::markerRangeForNode(Node* node, const String& markerType, unsigned index, ExceptionState& exceptionState)
+Range* Internals::markerRangeForNode(Node* node, const String& markerType, unsigned index, ExceptionState& exceptionState)
 {
     ASSERT(node);
     DocumentMarker* marker = markerAt(node, markerType, index, exceptionState);
@@ -1040,7 +1040,7 @@
     toHTMLFormControlElement(element)->setAutofilled(enabled);
 }
 
-RawPtr<Range> Internals::rangeFromLocationAndLength(Element* scope, int rangeLocation, int rangeLength)
+Range* Internals::rangeFromLocationAndLength(Element* scope, int rangeLocation, int rangeLength)
 {
     ASSERT(scope);
 
@@ -1486,7 +1486,7 @@
     return tags;
 }
 
-RawPtr<StaticNodeList> Internals::nodesFromRect(Document* document, int centerX, int centerY, unsigned topPadding, unsigned rightPadding,
+StaticNodeList* Internals::nodesFromRect(Document* document, int centerX, int centerY, unsigned topPadding, unsigned rightPadding,
     unsigned bottomPadding, unsigned leftPadding, bool ignoreClipping, bool allowChildFrameContent, ExceptionState& exceptionState) const
 {
     ASSERT(document);
diff --git a/third_party/WebKit/Source/core/testing/Internals.h b/third_party/WebKit/Source/core/testing/Internals.h
index c4ac2a5..3b6bd8b 100644
--- a/third_party/WebKit/Source/core/testing/Internals.h
+++ b/third_party/WebKit/Source/core/testing/Internals.h
@@ -94,9 +94,9 @@
 
     bool isSharingStyle(Element*, Element*) const;
 
-    RawPtr<CSSStyleDeclaration> computedStyleIncludingVisitedInfo(Node*) const;
+    CSSStyleDeclaration* computedStyleIncludingVisitedInfo(Node*) const;
 
-    RawPtr<ShadowRoot> createUserAgentShadowRoot(Element* host);
+    ShadowRoot* createUserAgentShadowRoot(Element* host);
 
     ShadowRoot* shadowRoot(Element* host);
     ShadowRoot* youngestShadowRoot(Element* host);
@@ -159,7 +159,7 @@
 
     unsigned markerCountForNode(Node*, const String&, ExceptionState&);
     unsigned activeMarkerCountForNode(Node*);
-    RawPtr<Range> markerRangeForNode(Node*, const String& markerType, unsigned index, ExceptionState&);
+    Range* markerRangeForNode(Node*, const String& markerType, unsigned index, ExceptionState&);
     String markerDescriptionForNode(Node*, const String& markerType, unsigned index, ExceptionState&);
     void addTextMatchMarker(const Range*, bool isActive);
     void setMarkersActive(Node*, unsigned startOffset, unsigned endOffset, bool);
@@ -174,7 +174,7 @@
     void setEditingValue(Element* inputElement, const String&, ExceptionState&);
     void setAutofilled(Element*, bool enabled, ExceptionState&);
 
-    RawPtr<Range> rangeFromLocationAndLength(Element* scope, int rangeLocation, int rangeLength);
+    Range* rangeFromLocationAndLength(Element* scope, int rangeLocation, int rangeLength);
     unsigned locationFromRange(Element* scope, const Range*);
     unsigned lengthFromRange(Element* scope, const Range*);
     String rangeAsText(const Range*);
@@ -205,7 +205,7 @@
     Vector<AtomicString> svgTags();
 
     // This is used to test rect based hit testing like what's done on touch screens.
-    RawPtr<StaticNodeList> nodesFromRect(Document*, int x, int y, unsigned topPadding, unsigned rightPadding,
+    StaticNodeList* nodesFromRect(Document*, int x, int y, unsigned topPadding, unsigned rightPadding,
         unsigned bottomPadding, unsigned leftPadding, bool ignoreClipping, bool allowChildFrameContent, ExceptionState&) const;
 
     bool hasSpellingMarker(Document*, int from, int length);
@@ -244,7 +244,7 @@
     unsigned numberOfLiveDocuments() const;
     String dumpRefCountedInstanceCounts() const;
     Vector<String> consoleMessageArgumentCounts(Document*) const;
-    RawPtr<LocalDOMWindow> openDummyInspectorFrontend(const String& url);
+    LocalDOMWindow* openDummyInspectorFrontend(const String& url);
     void closeDummyInspectorFrontend();
     Vector<unsigned long> setMemoryCacheCapacities(unsigned long minDeadBytes, unsigned long maxDeadBytes, unsigned long totalBytes);
 
diff --git a/third_party/WebKit/Source/core/testing/LayerRect.h b/third_party/WebKit/Source/core/testing/LayerRect.h
index d8f4084d..31a4857 100644
--- a/third_party/WebKit/Source/core/testing/LayerRect.h
+++ b/third_party/WebKit/Source/core/testing/LayerRect.h
@@ -46,7 +46,7 @@
 class LayerRect final : public GarbageCollectedFinalized<LayerRect>, public ScriptWrappable {
     DEFINE_WRAPPERTYPEINFO();
 public:
-    static LayerRect* create(RawPtr<Node> node, const String& layerType, int nodeOffsetX, int nodeOffsetY, ClientRect* rect)
+    static LayerRect* create(Node* node, const String& layerType, int nodeOffsetX, int nodeOffsetY, ClientRect* rect)
     {
         return new LayerRect(node, layerType, nodeOffsetX, nodeOffsetY, rect);
     }
@@ -64,7 +64,7 @@
     }
 
 private:
-    LayerRect(RawPtr<Node> node, const String& layerName, int nodeOffsetX, int nodeOffsetY, ClientRect* rect)
+    LayerRect(Node* node, const String& layerName, int nodeOffsetX, int nodeOffsetY, ClientRect* rect)
         : m_layerAssociatedNode(node)
         , m_layerType(layerName)
         , m_associatedNodeOffsetX(nodeOffsetX)
diff --git a/third_party/WebKit/Source/core/testing/LayerRectList.cpp b/third_party/WebKit/Source/core/testing/LayerRectList.cpp
index 4364eee5..943cbeb7 100644
--- a/third_party/WebKit/Source/core/testing/LayerRectList.cpp
+++ b/third_party/WebKit/Source/core/testing/LayerRectList.cpp
@@ -53,7 +53,7 @@
     return m_list[index].get();
 }
 
-void LayerRectList::append(RawPtr<Node> layerRootNode, const String& layerType, int layerOffsetX, int layerOffsetY, ClientRect* layerRelativeRect)
+void LayerRectList::append(Node* layerRootNode, const String& layerType, int layerOffsetX, int layerOffsetY, ClientRect* layerRelativeRect)
 {
     m_list.append(LayerRect::create(layerRootNode, layerType, layerOffsetX, layerOffsetY, layerRelativeRect));
 }
diff --git a/third_party/WebKit/Source/core/testing/LayerRectList.h b/third_party/WebKit/Source/core/testing/LayerRectList.h
index 5fe14dc4..9cefd5ab 100644
--- a/third_party/WebKit/Source/core/testing/LayerRectList.h
+++ b/third_party/WebKit/Source/core/testing/LayerRectList.h
@@ -53,7 +53,7 @@
 
     unsigned length() const;
     LayerRect* item(unsigned index);
-    void append(RawPtr<Node> layerAssociatedNode, const String& layerName, int layerOffsetX, int layerOffsetY, ClientRect* layerRelativeRect);
+    void append(Node* layerAssociatedNode, const String& layerName, int layerOffsetX, int layerOffsetY, ClientRect* layerRelativeRect);
 
     DECLARE_TRACE();
 
diff --git a/third_party/WebKit/Source/core/timing/PerformanceNavigation.h b/third_party/WebKit/Source/core/timing/PerformanceNavigation.h
index 2a72f1a2..2357027 100644
--- a/third_party/WebKit/Source/core/timing/PerformanceNavigation.h
+++ b/third_party/WebKit/Source/core/timing/PerformanceNavigation.h
@@ -40,7 +40,7 @@
 
 class LocalFrame;
 
-class CORE_EXPORT PerformanceNavigation final : public GarbageCollectedFinalized<PerformanceNavigation>, public ScriptWrappable, public DOMWindowProperty {
+class CORE_EXPORT PerformanceNavigation final : public GarbageCollected<PerformanceNavigation>, public ScriptWrappable, public DOMWindowProperty {
     DEFINE_WRAPPERTYPEINFO();
     USING_GARBAGE_COLLECTED_MIXIN(PerformanceNavigation);
 public:
diff --git a/third_party/WebKit/Source/core/timing/PerformanceTiming.h b/third_party/WebKit/Source/core/timing/PerformanceTiming.h
index ac6a23b..99eba79a 100644
--- a/third_party/WebKit/Source/core/timing/PerformanceTiming.h
+++ b/third_party/WebKit/Source/core/timing/PerformanceTiming.h
@@ -48,7 +48,7 @@
 class ScriptState;
 class ScriptValue;
 
-class CORE_EXPORT PerformanceTiming final : public GarbageCollectedFinalized<PerformanceTiming>, public ScriptWrappable, public DOMWindowProperty {
+class CORE_EXPORT PerformanceTiming final : public GarbageCollected<PerformanceTiming>, public ScriptWrappable, public DOMWindowProperty {
     DEFINE_WRAPPERTYPEINFO();
     USING_GARBAGE_COLLECTED_MIXIN(PerformanceTiming);
 public:
diff --git a/third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.cpp b/third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.cpp
index 34cc4dd..aa5e74e 100644
--- a/third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.cpp
+++ b/third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.cpp
@@ -42,17 +42,17 @@
 
 namespace blink {
 
-RawPtr<DedicatedWorkerGlobalScope> DedicatedWorkerGlobalScope::create(DedicatedWorkerThread* thread, PassOwnPtr<WorkerThreadStartupData> startupData, double timeOrigin)
+DedicatedWorkerGlobalScope* DedicatedWorkerGlobalScope::create(DedicatedWorkerThread* thread, PassOwnPtr<WorkerThreadStartupData> startupData, double timeOrigin)
 {
     // Note: startupData is finalized on return. After the relevant parts has been
     // passed along to the created 'context'.
-    RawPtr<DedicatedWorkerGlobalScope> context = new DedicatedWorkerGlobalScope(startupData->m_scriptURL, startupData->m_userAgent, thread, timeOrigin, startupData->m_starterOriginPrivilegeData.release(), startupData->m_workerClients.release());
+    DedicatedWorkerGlobalScope* context = new DedicatedWorkerGlobalScope(startupData->m_scriptURL, startupData->m_userAgent, thread, timeOrigin, startupData->m_starterOriginPrivilegeData.release(), startupData->m_workerClients.release());
     context->applyContentSecurityPolicyFromVector(*startupData->m_contentSecurityPolicyHeaders);
     context->setAddressSpace(startupData->m_addressSpace);
-    return context.release();
+    return context;
 }
 
-DedicatedWorkerGlobalScope::DedicatedWorkerGlobalScope(const KURL& url, const String& userAgent, DedicatedWorkerThread* thread, double timeOrigin, PassOwnPtr<SecurityOrigin::PrivilegeData> starterOriginPrivilegeData, RawPtr<WorkerClients> workerClients)
+DedicatedWorkerGlobalScope::DedicatedWorkerGlobalScope(const KURL& url, const String& userAgent, DedicatedWorkerThread* thread, double timeOrigin, PassOwnPtr<SecurityOrigin::PrivilegeData> starterOriginPrivilegeData, WorkerClients* workerClients)
     : WorkerGlobalScope(url, userAgent, thread, timeOrigin, starterOriginPrivilegeData, workerClients)
 {
 }
diff --git a/third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.h b/third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.h
index a9f2bf4..85a87c0 100644
--- a/third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.h
+++ b/third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.h
@@ -46,7 +46,7 @@
     DEFINE_WRAPPERTYPEINFO();
 public:
     typedef WorkerGlobalScope Base;
-    static RawPtr<DedicatedWorkerGlobalScope> create(DedicatedWorkerThread*, PassOwnPtr<WorkerThreadStartupData>, double timeOrigin);
+    static DedicatedWorkerGlobalScope* create(DedicatedWorkerThread*, PassOwnPtr<WorkerThreadStartupData>, double timeOrigin);
     ~DedicatedWorkerGlobalScope() override;
 
     bool isDedicatedWorkerGlobalScope() const override { return true; }
@@ -65,7 +65,7 @@
     DECLARE_VIRTUAL_TRACE();
 
 private:
-    DedicatedWorkerGlobalScope(const KURL&, const String& userAgent, DedicatedWorkerThread*, double timeOrigin, PassOwnPtr<SecurityOrigin::PrivilegeData>, RawPtr<WorkerClients>);
+    DedicatedWorkerGlobalScope(const KURL&, const String& userAgent, DedicatedWorkerThread*, double timeOrigin, PassOwnPtr<SecurityOrigin::PrivilegeData>, WorkerClients*);
 };
 
 } // namespace blink
diff --git a/third_party/WebKit/Source/core/workers/DedicatedWorkerMessagingProxy.cpp b/third_party/WebKit/Source/core/workers/DedicatedWorkerMessagingProxy.cpp
index 9d35077..37457c7 100644
--- a/third_party/WebKit/Source/core/workers/DedicatedWorkerMessagingProxy.cpp
+++ b/third_party/WebKit/Source/core/workers/DedicatedWorkerMessagingProxy.cpp
@@ -9,7 +9,7 @@
 
 namespace blink {
 
-DedicatedWorkerMessagingProxy::DedicatedWorkerMessagingProxy(InProcessWorkerBase* workerObject, RawPtr<WorkerClients> workerClients)
+DedicatedWorkerMessagingProxy::DedicatedWorkerMessagingProxy(InProcessWorkerBase* workerObject, WorkerClients* workerClients)
     : WorkerMessagingProxy(workerObject, workerClients)
 {
 }
diff --git a/third_party/WebKit/Source/core/workers/DedicatedWorkerMessagingProxy.h b/third_party/WebKit/Source/core/workers/DedicatedWorkerMessagingProxy.h
index 1e166769..ff081a8 100644
--- a/third_party/WebKit/Source/core/workers/DedicatedWorkerMessagingProxy.h
+++ b/third_party/WebKit/Source/core/workers/DedicatedWorkerMessagingProxy.h
@@ -14,7 +14,7 @@
     WTF_MAKE_NONCOPYABLE(DedicatedWorkerMessagingProxy);
     USING_FAST_MALLOC(WorkerMessagingProxy);
 public:
-    DedicatedWorkerMessagingProxy(InProcessWorkerBase*, RawPtr<WorkerClients>);
+    DedicatedWorkerMessagingProxy(InProcessWorkerBase*, WorkerClients*);
     ~DedicatedWorkerMessagingProxy() override;
 
     PassOwnPtr<WorkerThread> createWorkerThread(double originTime) override;
diff --git a/third_party/WebKit/Source/core/workers/DedicatedWorkerThread.cpp b/third_party/WebKit/Source/core/workers/DedicatedWorkerThread.cpp
index b1f6e4e..2681732 100644
--- a/third_party/WebKit/Source/core/workers/DedicatedWorkerThread.cpp
+++ b/third_party/WebKit/Source/core/workers/DedicatedWorkerThread.cpp
@@ -52,7 +52,7 @@
 {
 }
 
-RawPtr<WorkerGlobalScope> DedicatedWorkerThread::createWorkerGlobalScope(PassOwnPtr<WorkerThreadStartupData> startupData)
+WorkerGlobalScope* DedicatedWorkerThread::createWorkerGlobalScope(PassOwnPtr<WorkerThreadStartupData> startupData)
 {
     return DedicatedWorkerGlobalScope::create(this, startupData, m_timeOrigin);
 }
diff --git a/third_party/WebKit/Source/core/workers/DedicatedWorkerThread.h b/third_party/WebKit/Source/core/workers/DedicatedWorkerThread.h
index 8e9fb10..476d9e1 100644
--- a/third_party/WebKit/Source/core/workers/DedicatedWorkerThread.h
+++ b/third_party/WebKit/Source/core/workers/DedicatedWorkerThread.h
@@ -45,7 +45,7 @@
     ~DedicatedWorkerThread() override;
 
 protected:
-    RawPtr<WorkerGlobalScope> createWorkerGlobalScope(PassOwnPtr<WorkerThreadStartupData>) override;
+    WorkerGlobalScope* createWorkerGlobalScope(PassOwnPtr<WorkerThreadStartupData>) override;
     void postInitialize() override;
     WebThreadSupportingGC& backingThread() override;
 
diff --git a/third_party/WebKit/Source/core/workers/SharedWorkerGlobalScope.cpp b/third_party/WebKit/Source/core/workers/SharedWorkerGlobalScope.cpp
index 411e84f..57b8d4b 100644
--- a/third_party/WebKit/Source/core/workers/SharedWorkerGlobalScope.cpp
+++ b/third_party/WebKit/Source/core/workers/SharedWorkerGlobalScope.cpp
@@ -40,25 +40,25 @@
 
 namespace blink {
 
-RawPtr<MessageEvent> createConnectEvent(MessagePort* port)
+MessageEvent* createConnectEvent(MessagePort* port)
 {
-    RawPtr<MessageEvent> event = MessageEvent::create(new MessagePortArray(1, port), String(), String(), port);
+    MessageEvent* event = MessageEvent::create(new MessagePortArray(1, port), String(), String(), port);
     event->initEvent(EventTypeNames::connect, false, false);
-    return event.release();
+    return event;
 }
 
 // static
-RawPtr<SharedWorkerGlobalScope> SharedWorkerGlobalScope::create(const String& name, SharedWorkerThread* thread, PassOwnPtr<WorkerThreadStartupData> startupData)
+SharedWorkerGlobalScope* SharedWorkerGlobalScope::create(const String& name, SharedWorkerThread* thread, PassOwnPtr<WorkerThreadStartupData> startupData)
 {
     // Note: startupData is finalized on return. After the relevant parts has been
     // passed along to the created 'context'.
-    RawPtr<SharedWorkerGlobalScope> context = new SharedWorkerGlobalScope(name, startupData->m_scriptURL, startupData->m_userAgent, thread, startupData->m_starterOriginPrivilegeData.release(), startupData->m_workerClients.release());
+    SharedWorkerGlobalScope* context = new SharedWorkerGlobalScope(name, startupData->m_scriptURL, startupData->m_userAgent, thread, startupData->m_starterOriginPrivilegeData.release(), startupData->m_workerClients.release());
     context->applyContentSecurityPolicyFromVector(*startupData->m_contentSecurityPolicyHeaders);
     context->setAddressSpace(startupData->m_addressSpace);
-    return context.release();
+    return context;
 }
 
-SharedWorkerGlobalScope::SharedWorkerGlobalScope(const String& name, const KURL& url, const String& userAgent, SharedWorkerThread* thread, PassOwnPtr<SecurityOrigin::PrivilegeData> starterOriginPrivilegeData, RawPtr<WorkerClients> workerClients)
+SharedWorkerGlobalScope::SharedWorkerGlobalScope(const String& name, const KURL& url, const String& userAgent, SharedWorkerThread* thread, PassOwnPtr<SecurityOrigin::PrivilegeData> starterOriginPrivilegeData, WorkerClients* workerClients)
     : WorkerGlobalScope(url, userAgent, thread, monotonicallyIncreasingTime(), starterOriginPrivilegeData, workerClients)
     , m_name(name)
 {
@@ -81,10 +81,10 @@
 void SharedWorkerGlobalScope::logExceptionToConsole(const String& errorMessage, int scriptId, const String& sourceURL, int lineNumber, int columnNumber, PassRefPtr<ScriptCallStack> callStack)
 {
     WorkerGlobalScope::logExceptionToConsole(errorMessage, scriptId, sourceURL, lineNumber, columnNumber, callStack);
-    RawPtr<ConsoleMessage> consoleMessage = ConsoleMessage::create(JSMessageSource, ErrorMessageLevel, errorMessage, sourceURL, lineNumber, columnNumber);
+    ConsoleMessage* consoleMessage = ConsoleMessage::create(JSMessageSource, ErrorMessageLevel, errorMessage, sourceURL, lineNumber, columnNumber);
     consoleMessage->setScriptId(scriptId);
     consoleMessage->setCallStack(callStack);
-    addMessageToWorkerConsole(consoleMessage.release());
+    addMessageToWorkerConsole(consoleMessage);
 }
 
 DEFINE_TRACE(SharedWorkerGlobalScope)
diff --git a/third_party/WebKit/Source/core/workers/SharedWorkerGlobalScope.h b/third_party/WebKit/Source/core/workers/SharedWorkerGlobalScope.h
index f1b5f218..852ad2a 100644
--- a/third_party/WebKit/Source/core/workers/SharedWorkerGlobalScope.h
+++ b/third_party/WebKit/Source/core/workers/SharedWorkerGlobalScope.h
@@ -46,7 +46,7 @@
     DEFINE_WRAPPERTYPEINFO();
 public:
     typedef WorkerGlobalScope Base;
-    static RawPtr<SharedWorkerGlobalScope> create(const String& name, SharedWorkerThread*, PassOwnPtr<WorkerThreadStartupData>);
+    static SharedWorkerGlobalScope* create(const String& name, SharedWorkerThread*, PassOwnPtr<WorkerThreadStartupData>);
     ~SharedWorkerGlobalScope() override;
 
     bool isSharedWorkerGlobalScope() const override { return true; }
@@ -63,13 +63,13 @@
     DECLARE_VIRTUAL_TRACE();
 
 private:
-    SharedWorkerGlobalScope(const String& name, const KURL&, const String& userAgent, SharedWorkerThread*, PassOwnPtr<SecurityOrigin::PrivilegeData>, RawPtr<WorkerClients>);
+    SharedWorkerGlobalScope(const String& name, const KURL&, const String& userAgent, SharedWorkerThread*, PassOwnPtr<SecurityOrigin::PrivilegeData>, WorkerClients*);
     void logExceptionToConsole(const String& errorMessage, int scriptId, const String& sourceURL, int lineNumber, int columnNumber, PassRefPtr<ScriptCallStack>) override;
 
     String m_name;
 };
 
-CORE_EXPORT RawPtr<MessageEvent> createConnectEvent(MessagePort*);
+CORE_EXPORT MessageEvent* createConnectEvent(MessagePort*);
 
 } // namespace blink
 
diff --git a/third_party/WebKit/Source/core/workers/SharedWorkerThread.cpp b/third_party/WebKit/Source/core/workers/SharedWorkerThread.cpp
index 393fda5e..69a0d2b 100644
--- a/third_party/WebKit/Source/core/workers/SharedWorkerThread.cpp
+++ b/third_party/WebKit/Source/core/workers/SharedWorkerThread.cpp
@@ -50,7 +50,7 @@
 {
 }
 
-RawPtr<WorkerGlobalScope> SharedWorkerThread::createWorkerGlobalScope(PassOwnPtr<WorkerThreadStartupData> startupData)
+WorkerGlobalScope* SharedWorkerThread::createWorkerGlobalScope(PassOwnPtr<WorkerThreadStartupData> startupData)
 {
     return SharedWorkerGlobalScope::create(m_name, this, startupData);
 }
diff --git a/third_party/WebKit/Source/core/workers/SharedWorkerThread.h b/third_party/WebKit/Source/core/workers/SharedWorkerThread.h
index 28d7a217..8e2f07d 100644
--- a/third_party/WebKit/Source/core/workers/SharedWorkerThread.h
+++ b/third_party/WebKit/Source/core/workers/SharedWorkerThread.h
@@ -44,7 +44,7 @@
     ~SharedWorkerThread() override;
 
 protected:
-    RawPtr<WorkerGlobalScope> createWorkerGlobalScope(PassOwnPtr<WorkerThreadStartupData>) override;
+    WorkerGlobalScope* createWorkerGlobalScope(PassOwnPtr<WorkerThreadStartupData>) override;
     WebThreadSupportingGC& backingThread() override;
 
 private:
diff --git a/third_party/WebKit/Source/core/workers/WorkerEventQueue.cpp b/third_party/WebKit/Source/core/workers/WorkerEventQueue.cpp
index c05bba0..dd9f064 100644
--- a/third_party/WebKit/Source/core/workers/WorkerEventQueue.cpp
+++ b/third_party/WebKit/Source/core/workers/WorkerEventQueue.cpp
@@ -33,7 +33,7 @@
 
 namespace blink {
 
-RawPtr<WorkerEventQueue> WorkerEventQueue::create(ExecutionContext* context)
+WorkerEventQueue* WorkerEventQueue::create(ExecutionContext* context)
 {
     return new WorkerEventQueue(context);
 }
@@ -58,7 +58,7 @@
 
 class WorkerEventQueue::EventDispatcherTask : public ExecutionContextTask {
 public:
-    static PassOwnPtr<EventDispatcherTask> create(RawPtr<Event> event, WorkerEventQueue* eventQueue)
+    static PassOwnPtr<EventDispatcherTask> create(Event* event, WorkerEventQueue* eventQueue)
     {
         return adoptPtr(new EventDispatcherTask(event, eventQueue));
     }
@@ -69,13 +69,8 @@
             m_eventQueue->removeEvent(m_event.get());
     }
 
-    void dispatchEvent(ExecutionContext* context, RawPtr<Event> prpEvent)
+    void dispatchEvent(ExecutionContext* context, Event* event)
     {
-        // Stash the event on the stack in a RawPtr; trying to do this
-        // in a single line causes an optimization bug with MSVC. MSVC generates code
-        // that passes the event arg (forcing RawPtr to be released)
-        // before the target is queried.
-        RawPtr<Event> event = prpEvent;
         InspectorInstrumentation::AsyncTask asyncTask(context, event);
         event->target()->dispatchEvent(event);
     }
@@ -96,7 +91,7 @@
     }
 
 private:
-    EventDispatcherTask(RawPtr<Event> event, WorkerEventQueue* eventQueue)
+    EventDispatcherTask(Event* event, WorkerEventQueue* eventQueue)
         : m_event(event)
         , m_eventQueue(eventQueue)
         , m_isCancelled(false)
diff --git a/third_party/WebKit/Source/core/workers/WorkerEventQueue.h b/third_party/WebKit/Source/core/workers/WorkerEventQueue.h
index f82efed..d3c36d14 100644
--- a/third_party/WebKit/Source/core/workers/WorkerEventQueue.h
+++ b/third_party/WebKit/Source/core/workers/WorkerEventQueue.h
@@ -41,7 +41,7 @@
 class WorkerEventQueue final : public EventQueue {
 public:
 
-    static RawPtr<WorkerEventQueue> create(ExecutionContext*);
+    static WorkerEventQueue* create(ExecutionContext*);
     ~WorkerEventQueue() override;
     DECLARE_TRACE();
 
diff --git a/third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp b/third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp
index 69ef5d0..e74f777a 100644
--- a/third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp
+++ b/third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp
@@ -71,7 +71,7 @@
 
 namespace blink {
 
-WorkerGlobalScope::WorkerGlobalScope(const KURL& url, const String& userAgent, WorkerThread* thread, double timeOrigin, PassOwnPtr<SecurityOrigin::PrivilegeData> starterOriginPrivilageData, RawPtr<WorkerClients> workerClients)
+WorkerGlobalScope::WorkerGlobalScope(const KURL& url, const String& userAgent, WorkerThread* thread, double timeOrigin, PassOwnPtr<SecurityOrigin::PrivilegeData> starterOriginPrivilageData, WorkerClients* workerClients)
     : m_url(url)
     , m_userAgent(userAgent)
     , m_v8CacheOptions(V8CacheOptionsDefault)
@@ -103,7 +103,7 @@
 void WorkerGlobalScope::applyContentSecurityPolicyFromVector(const Vector<CSPHeaderAndType>& headers)
 {
     if (!contentSecurityPolicy()) {
-        RawPtr<ContentSecurityPolicy> csp = ContentSecurityPolicy::create();
+        ContentSecurityPolicy* csp = ContentSecurityPolicy::create();
         setContentSecurityPolicy(csp);
     }
     for (const auto& policyAndType : headers)
@@ -206,7 +206,7 @@
     // Event listeners would keep DOMWrapperWorld objects alive for too long. Also, they have references to JS objects,
     // which become dangling once Heap is destroyed.
     for (auto it = m_eventListeners.begin(); it != m_eventListeners.end(); ) {
-        RawPtr<V8AbstractEventListener> listener = *it;
+        V8AbstractEventListener* listener = *it;
         // clearListenerObject() will unregister the listener from
         // m_eventListeners, and invalidate the iterator, so we have to advance
         // it first.
@@ -269,12 +269,12 @@
         InspectorInstrumentation::scriptImported(&executionContext, scriptLoader->identifier(), scriptLoader->script());
         scriptLoaded(scriptLoader->script().length(), scriptLoader->cachedMetadata() ? scriptLoader->cachedMetadata()->size() : 0);
 
-        RawPtr<ErrorEvent> errorEvent = nullptr;
+        ErrorEvent* errorEvent = nullptr;
         OwnPtr<Vector<char>> cachedMetaData(scriptLoader->releaseCachedMetadata());
-        RawPtr<CachedMetadataHandler> handler(createWorkerScriptCachedMetadataHandler(completeURL, cachedMetaData.get()));
-        m_scriptController->evaluate(ScriptSourceCode(scriptLoader->script(), scriptLoader->responseURL()), &errorEvent, handler.get(), m_v8CacheOptions);
+        CachedMetadataHandler* handler(createWorkerScriptCachedMetadataHandler(completeURL, cachedMetaData.get()));
+        m_scriptController->evaluate(ScriptSourceCode(scriptLoader->script(), scriptLoader->responseURL()), &errorEvent, handler, m_v8CacheOptions);
         if (errorEvent) {
-            m_scriptController->rethrowExceptionFromImportedScript(errorEvent.release(), exceptionState);
+            m_scriptController->rethrowExceptionFromImportedScript(errorEvent, exceptionState);
             return;
         }
     }
@@ -288,7 +288,7 @@
 void WorkerGlobalScope::logExceptionToConsole(const String& errorMessage, int, const String& sourceURL, int lineNumber, int columnNumber, PassRefPtr<ScriptCallStack> callStack)
 {
     unsigned long exceptionId = ++m_workerExceptionUniqueIdentifier;
-    RawPtr<ConsoleMessage> consoleMessage = ConsoleMessage::create(JSMessageSource, ErrorMessageLevel, errorMessage, sourceURL, lineNumber, columnNumber);
+    ConsoleMessage* consoleMessage = ConsoleMessage::create(JSMessageSource, ErrorMessageLevel, errorMessage, sourceURL, lineNumber, columnNumber);
     consoleMessage->setCallStack(callStack);
     m_pendingMessages.set(exceptionId, consoleMessage);
 
@@ -303,12 +303,12 @@
 void WorkerGlobalScope::addConsoleMessage(RawPtr<ConsoleMessage> prpConsoleMessage)
 {
     ASSERT(isContextThread());
-    RawPtr<ConsoleMessage> consoleMessage = prpConsoleMessage;
+    ConsoleMessage* consoleMessage = prpConsoleMessage;
     thread()->workerReportingProxy().reportConsoleMessage(consoleMessage);
-    addMessageToWorkerConsole(consoleMessage.release());
+    addMessageToWorkerConsole(consoleMessage);
 }
 
-void WorkerGlobalScope::addMessageToWorkerConsole(RawPtr<ConsoleMessage> consoleMessage)
+void WorkerGlobalScope::addMessageToWorkerConsole(ConsoleMessage* consoleMessage)
 {
     ASSERT(isContextThread());
     m_messageStorage->reportMessage(this, consoleMessage);
@@ -369,9 +369,9 @@
 
 void WorkerGlobalScope::exceptionHandled(int exceptionId, bool isHandled)
 {
-    RawPtr<ConsoleMessage> consoleMessage = m_pendingMessages.take(exceptionId);
+    ConsoleMessage* consoleMessage = m_pendingMessages.take(exceptionId);
     if (!isHandled)
-        addConsoleMessage(consoleMessage.release());
+        addConsoleMessage(consoleMessage);
 }
 
 bool WorkerGlobalScope::isSecureContext(String& errorMessage, const SecureContextCheck privilegeContextCheck) const
diff --git a/third_party/WebKit/Source/core/workers/WorkerGlobalScope.h b/third_party/WebKit/Source/core/workers/WorkerGlobalScope.h
index 4cfc430..d44e2862 100644
--- a/third_party/WebKit/Source/core/workers/WorkerGlobalScope.h
+++ b/third_party/WebKit/Source/core/workers/WorkerGlobalScope.h
@@ -109,7 +109,7 @@
     // WorkerUtils
     virtual void importScripts(const Vector<String>& urls, ExceptionState&);
     // Returns null if caching is not supported.
-    virtual RawPtr<CachedMetadataHandler> createWorkerScriptCachedMetadataHandler(const KURL& scriptURL, const Vector<char>* metaData) { return nullptr; }
+    virtual CachedMetadataHandler* createWorkerScriptCachedMetadataHandler(const KURL& scriptURL, const Vector<char>* metaData) { return nullptr; }
 
     WorkerNavigator* navigator() const;
 
@@ -152,11 +152,11 @@
     DECLARE_VIRTUAL_TRACE();
 
 protected:
-    WorkerGlobalScope(const KURL&, const String& userAgent, WorkerThread*, double timeOrigin, PassOwnPtr<SecurityOrigin::PrivilegeData>, RawPtr<WorkerClients>);
+    WorkerGlobalScope(const KURL&, const String& userAgent, WorkerThread*, double timeOrigin, PassOwnPtr<SecurityOrigin::PrivilegeData>, WorkerClients*);
     void applyContentSecurityPolicyFromVector(const Vector<CSPHeaderAndType>& headers);
 
     void logExceptionToConsole(const String& errorMessage, int scriptId, const String& sourceURL, int lineNumber, int columnNumber, PassRefPtr<ScriptCallStack>) override;
-    void addMessageToWorkerConsole(RawPtr<ConsoleMessage>);
+    void addMessageToWorkerConsole(ConsoleMessage*);
     void setV8CacheOptions(V8CacheOptions v8CacheOptions) { m_v8CacheOptions = v8CacheOptions; }
 
     void removeURLFromMemoryCache(const KURL&) override;
diff --git a/third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxyProvider.cpp b/third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxyProvider.cpp
index 5a764e1a..6a28ca8f 100644
--- a/third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxyProvider.cpp
+++ b/third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxyProvider.cpp
@@ -44,7 +44,7 @@
     return "WorkerGlobalScopeProxyProvider";
 }
 
-void provideWorkerGlobalScopeProxyProviderTo(Page& page, RawPtr<WorkerGlobalScopeProxyProvider> provider)
+void provideWorkerGlobalScopeProxyProviderTo(Page& page, WorkerGlobalScopeProxyProvider* provider)
 {
     Supplement<Page>::provideTo(page, WorkerGlobalScopeProxyProvider::supplementName(), provider);
 }
diff --git a/third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxyProvider.h b/third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxyProvider.h
index fe05526c..a31cdb3 100644
--- a/third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxyProvider.h
+++ b/third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxyProvider.h
@@ -55,7 +55,7 @@
     static const char* supplementName();
 };
 
-CORE_EXPORT void provideWorkerGlobalScopeProxyProviderTo(Page&, RawPtr<WorkerGlobalScopeProxyProvider>);
+CORE_EXPORT void provideWorkerGlobalScopeProxyProviderTo(Page&, WorkerGlobalScopeProxyProvider*);
 
 } // namespace blink
 
diff --git a/third_party/WebKit/Source/core/workers/WorkerInspectorProxy.cpp b/third_party/WebKit/Source/core/workers/WorkerInspectorProxy.cpp
index db48fbc..8323d2b 100644
--- a/third_party/WebKit/Source/core/workers/WorkerInspectorProxy.cpp
+++ b/third_party/WebKit/Source/core/workers/WorkerInspectorProxy.cpp
@@ -39,7 +39,7 @@
 {
 }
 
-RawPtr<WorkerInspectorProxy> WorkerInspectorProxy::create()
+WorkerInspectorProxy* WorkerInspectorProxy::create()
 {
     return new WorkerInspectorProxy();
 }
diff --git a/third_party/WebKit/Source/core/workers/WorkerInspectorProxy.h b/third_party/WebKit/Source/core/workers/WorkerInspectorProxy.h
index 36e281e4..f1a409f 100644
--- a/third_party/WebKit/Source/core/workers/WorkerInspectorProxy.h
+++ b/third_party/WebKit/Source/core/workers/WorkerInspectorProxy.h
@@ -21,7 +21,7 @@
 // All of these methods should be called on the main thread.
 class CORE_EXPORT WorkerInspectorProxy final : public GarbageCollectedFinalized<WorkerInspectorProxy> {
 public:
-    static RawPtr<WorkerInspectorProxy> create();
+    static WorkerInspectorProxy* create();
 
     ~WorkerInspectorProxy();
     DECLARE_TRACE();
diff --git a/third_party/WebKit/Source/core/workers/WorkerMessagingProxy.cpp b/third_party/WebKit/Source/core/workers/WorkerMessagingProxy.cpp
index 272bda7..2cb6690 100644
--- a/third_party/WebKit/Source/core/workers/WorkerMessagingProxy.cpp
+++ b/third_party/WebKit/Source/core/workers/WorkerMessagingProxy.cpp
@@ -71,7 +71,7 @@
 
 } // namespace
 
-WorkerMessagingProxy::WorkerMessagingProxy(InProcessWorkerBase* workerObject, RawPtr<WorkerClients> workerClients)
+WorkerMessagingProxy::WorkerMessagingProxy(InProcessWorkerBase* workerObject, WorkerClients* workerClients)
     : m_executionContext(workerObject->getExecutionContext())
     , m_workerObjectProxy(WorkerObjectProxy::create(this))
     , m_workerObject(workerObject)
@@ -169,7 +169,7 @@
     // We don't bother checking the askedToTerminate() flag here, because exceptions should *always* be reported even if the thread is terminated.
     // This is intentionally different than the behavior in MessageWorkerTask, because terminated workers no longer deliver messages (section 4.6 of the WebWorker spec), but they do report exceptions.
 
-    RawPtr<ErrorEvent> event = ErrorEvent::create(errorMessage, sourceURL, lineNumber, columnNumber, nullptr);
+    ErrorEvent* event = ErrorEvent::create(errorMessage, sourceURL, lineNumber, columnNumber, nullptr);
     DispatchEventResult dispatchResult = m_workerObject->dispatchEvent(event);
     postTaskToWorkerGlobalScope(createCrossThreadTask(&processExceptionOnWorkerGlobalScope, exceptionId, dispatchResult != DispatchEventResult::NotCanceled));
 }
@@ -185,9 +185,9 @@
     if (!frame)
         return;
 
-    RawPtr<ConsoleMessage> consoleMessage = ConsoleMessage::create(source, level, message, sourceURL, lineNumber);
+    ConsoleMessage* consoleMessage = ConsoleMessage::create(source, level, message, sourceURL, lineNumber);
     consoleMessage->setWorkerInspectorProxy(m_workerInspectorProxy.get());
-    frame->console().addMessage(consoleMessage.release());
+    frame->console().addMessage(consoleMessage);
 }
 
 void WorkerMessagingProxy::workerThreadCreated()
diff --git a/third_party/WebKit/Source/core/workers/WorkerMessagingProxy.h b/third_party/WebKit/Source/core/workers/WorkerMessagingProxy.h
index 617ce7d..1810ccd 100644
--- a/third_party/WebKit/Source/core/workers/WorkerMessagingProxy.h
+++ b/third_party/WebKit/Source/core/workers/WorkerMessagingProxy.h
@@ -76,7 +76,7 @@
     ExecutionContext* getExecutionContext() const { return m_executionContext.get(); }
 
 protected:
-    WorkerMessagingProxy(InProcessWorkerBase*, RawPtr<WorkerClients>);
+    WorkerMessagingProxy(InProcessWorkerBase*, WorkerClients*);
     ~WorkerMessagingProxy() override;
 
     virtual PassOwnPtr<WorkerThread> createWorkerThread(double originTime) = 0;
diff --git a/third_party/WebKit/Source/core/workers/WorkerScriptLoader.h b/third_party/WebKit/Source/core/workers/WorkerScriptLoader.h
index cd96284..29d62577 100644
--- a/third_party/WebKit/Source/core/workers/WorkerScriptLoader.h
+++ b/third_party/WebKit/Source/core/workers/WorkerScriptLoader.h
@@ -80,7 +80,7 @@
     const Vector<char>* cachedMetadata() const { return m_cachedMetadata.get(); }
 
     ContentSecurityPolicy* contentSecurityPolicy() { return m_contentSecurityPolicy.get(); }
-    RawPtr<ContentSecurityPolicy> releaseContentSecurityPolicy() { return m_contentSecurityPolicy.release(); }
+    ContentSecurityPolicy* releaseContentSecurityPolicy() { return m_contentSecurityPolicy.release(); }
 
     WebAddressSpace responseAddressSpace() const { return m_responseAddressSpace; }
 
diff --git a/third_party/WebKit/Source/core/workers/WorkerThread.cpp b/third_party/WebKit/Source/core/workers/WorkerThread.cpp
index edd99424..f9f67b0 100644
--- a/third_party/WebKit/Source/core/workers/WorkerThread.cpp
+++ b/third_party/WebKit/Source/core/workers/WorkerThread.cpp
@@ -229,8 +229,8 @@
         m_workerReportingProxy.didInitializeWorkerContext();
     }
 
-    RawPtr<CachedMetadataHandler> handler(workerGlobalScope()->createWorkerScriptCachedMetadataHandler(scriptURL, cachedMetaData.get()));
-    bool success = m_workerGlobalScope->scriptController()->evaluate(ScriptSourceCode(sourceCode, scriptURL), nullptr, handler.get(), v8CacheOptions);
+    CachedMetadataHandler* handler = workerGlobalScope()->createWorkerScriptCachedMetadataHandler(scriptURL, cachedMetaData.get());
+    bool success = m_workerGlobalScope->scriptController()->evaluate(ScriptSourceCode(sourceCode, scriptURL), nullptr, handler, v8CacheOptions);
     m_workerGlobalScope->didEvaluateWorkerScript();
     m_workerReportingProxy.didEvaluateWorkerScript(success);
 
diff --git a/third_party/WebKit/Source/core/workers/WorkerThread.h b/third_party/WebKit/Source/core/workers/WorkerThread.h
index 02f7a8bd..7b407ed 100644
--- a/third_party/WebKit/Source/core/workers/WorkerThread.h
+++ b/third_party/WebKit/Source/core/workers/WorkerThread.h
@@ -118,7 +118,7 @@
     WorkerThread(PassRefPtr<WorkerLoaderProxy>, WorkerReportingProxy&);
 
     // Factory method for creating a new worker context for the thread.
-    virtual RawPtr<WorkerGlobalScope> createWorkerGlobalScope(PassOwnPtr<WorkerThreadStartupData>) = 0;
+    virtual WorkerGlobalScope* createWorkerGlobalScope(PassOwnPtr<WorkerThreadStartupData>) = 0;
 
     virtual void postInitialize() { }
 
@@ -160,7 +160,7 @@
 
     RefPtr<WorkerLoaderProxy> m_workerLoaderProxy;
     WorkerReportingProxy& m_workerReportingProxy;
-    RawPtr<WebScheduler> m_webScheduler; // Not owned.
+    WebScheduler* m_webScheduler; // Not owned.
 
     // This lock protects |m_workerGlobalScope|, |m_terminated|, |m_shutdown|, |m_isolate|, |m_runningDebuggerTask|, |m_shouldTerminateV8Execution| and |m_microtaskRunner|.
     Mutex m_threadStateMutex;
diff --git a/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.cpp b/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.cpp
index 63697685..8e21d8a 100644
--- a/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.cpp
+++ b/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.cpp
@@ -34,7 +34,7 @@
 
 namespace blink {
 
-WorkerThreadStartupData::WorkerThreadStartupData(const KURL& scriptURL, const String& userAgent, const String& sourceCode, PassOwnPtr<Vector<char>> cachedMetaData, WorkerThreadStartMode startMode, const PassOwnPtr<Vector<CSPHeaderAndType>> contentSecurityPolicyHeaders, const SecurityOrigin* starterOrigin, RawPtr<WorkerClients> workerClients, WebAddressSpace addressSpace, V8CacheOptions v8CacheOptions)
+WorkerThreadStartupData::WorkerThreadStartupData(const KURL& scriptURL, const String& userAgent, const String& sourceCode, PassOwnPtr<Vector<char>> cachedMetaData, WorkerThreadStartMode startMode, const PassOwnPtr<Vector<CSPHeaderAndType>> contentSecurityPolicyHeaders, const SecurityOrigin* starterOrigin, WorkerClients* workerClients, WebAddressSpace addressSpace, V8CacheOptions v8CacheOptions)
     : m_scriptURL(scriptURL.copy())
     , m_userAgent(userAgent.isolatedCopy())
     , m_sourceCode(sourceCode.isolatedCopy())
diff --git a/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.h b/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.h
index 7bfa82e27..48a4ed9 100644
--- a/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.h
+++ b/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.h
@@ -50,7 +50,7 @@
     WTF_MAKE_NONCOPYABLE(WorkerThreadStartupData);
     USING_FAST_MALLOC(WorkerThreadStartupData);
 public:
-    static PassOwnPtr<WorkerThreadStartupData> create(const KURL& scriptURL, const String& userAgent, const String& sourceCode, PassOwnPtr<Vector<char>> cachedMetaData, WorkerThreadStartMode startMode, const PassOwnPtr<Vector<CSPHeaderAndType>> contentSecurityPolicyHeaders, const SecurityOrigin* starterOrigin, RawPtr<WorkerClients> workerClients, WebAddressSpace addressSpace, V8CacheOptions v8CacheOptions = V8CacheOptionsDefault)
+    static PassOwnPtr<WorkerThreadStartupData> create(const KURL& scriptURL, const String& userAgent, const String& sourceCode, PassOwnPtr<Vector<char>> cachedMetaData, WorkerThreadStartMode startMode, const PassOwnPtr<Vector<CSPHeaderAndType>> contentSecurityPolicyHeaders, const SecurityOrigin* starterOrigin, WorkerClients* workerClients, WebAddressSpace addressSpace, V8CacheOptions v8CacheOptions = V8CacheOptionsDefault)
     {
         return adoptPtr(new WorkerThreadStartupData(scriptURL, userAgent, sourceCode, cachedMetaData, startMode, contentSecurityPolicyHeaders, starterOrigin, workerClients, addressSpace, v8CacheOptions));
     }
@@ -91,7 +91,7 @@
     V8CacheOptions m_v8CacheOptions;
 
 private:
-    WorkerThreadStartupData(const KURL& scriptURL, const String& userAgent, const String& sourceCode, PassOwnPtr<Vector<char>> cachedMetaData, WorkerThreadStartMode, const PassOwnPtr<Vector<CSPHeaderAndType>> contentSecurityPolicyHeaders, const SecurityOrigin*, RawPtr<WorkerClients>, WebAddressSpace, V8CacheOptions);
+    WorkerThreadStartupData(const KURL& scriptURL, const String& userAgent, const String& sourceCode, PassOwnPtr<Vector<char>> cachedMetaData, WorkerThreadStartMode, const PassOwnPtr<Vector<CSPHeaderAndType>> contentSecurityPolicyHeaders, const SecurityOrigin*, WorkerClients*, WebAddressSpace, V8CacheOptions);
 };
 
 } // namespace blink
diff --git a/third_party/WebKit/Source/core/workers/WorkerThreadTestHelper.h b/third_party/WebKit/Source/core/workers/WorkerThreadTestHelper.h
index 6cad1567..f6a96c5 100644
--- a/third_party/WebKit/Source/core/workers/WorkerThreadTestHelper.h
+++ b/third_party/WebKit/Source/core/workers/WorkerThreadTestHelper.h
@@ -69,7 +69,7 @@
 public:
     typedef WorkerGlobalScope Base;
 
-    FakeWorkerGlobalScope(const KURL& url, const String& userAgent, WorkerThread* thread, PassOwnPtr<SecurityOrigin::PrivilegeData> starterOriginPrivilegeData, RawPtr<WorkerClients> workerClients)
+    FakeWorkerGlobalScope(const KURL& url, const String& userAgent, WorkerThread* thread, PassOwnPtr<SecurityOrigin::PrivilegeData> starterOriginPrivilegeData, WorkerClients* workerClients)
         : WorkerGlobalScope(url, userAgent, thread, monotonicallyIncreasingTime(), starterOriginPrivilegeData, workerClients)
         , m_thread(thread)
     {
@@ -124,7 +124,7 @@
         WorkerThread::willDestroyIsolate();
     }
 
-    RawPtr<WorkerGlobalScope> createWorkerGlobalScope(PassOwnPtr<WorkerThreadStartupData> startupData) override
+    WorkerGlobalScope* createWorkerGlobalScope(PassOwnPtr<WorkerThreadStartupData> startupData) override
     {
         return new FakeWorkerGlobalScope(startupData->m_scriptURL, startupData->m_userAgent, this, startupData->m_starterOriginPrivilegeData.release(), startupData->m_workerClients.release());
     }
@@ -145,7 +145,7 @@
         CSPHeaderAndType headerAndType("contentSecurityPolicy", ContentSecurityPolicyHeaderTypeReport);
         headers->append(headerAndType);
 
-        RawPtr<WorkerClients> clients = nullptr;
+        WorkerClients* clients = nullptr;
 
         start(WorkerThreadStartupData::create(
             KURL(ParsedURLString, "http://fake.url/"),
@@ -155,7 +155,7 @@
             DontPauseWorkerGlobalScopeOnStart,
             headers.release(),
             securityOrigin,
-            clients.release(),
+            clients,
             WebAddressSpaceLocal,
             V8CacheOptionsDefault));
     }
diff --git a/third_party/WebKit/Source/core/xml/XPathNodeSet.cpp b/third_party/WebKit/Source/core/xml/XPathNodeSet.cpp
index 5a52d5b..15bbf16 100644
--- a/third_party/WebKit/Source/core/xml/XPathNodeSet.cpp
+++ b/third_party/WebKit/Source/core/xml/XPathNodeSet.cpp
@@ -199,7 +199,7 @@
 {
     if (node->isAttributeNode())
         node = toAttr(node)->ownerElement();
-    if (node->inDocument()) {
+    if (node->inShadowIncludingDocument()) {
         node = &node->document();
     } else {
         while (Node* parent = node->parentNode())
diff --git a/third_party/WebKit/Source/core/xml/XPathPath.cpp b/third_party/WebKit/Source/core/xml/XPathPath.cpp
index 52f3b44..7b8caca0 100644
--- a/third_party/WebKit/Source/core/xml/XPathPath.cpp
+++ b/third_party/WebKit/Source/core/xml/XPathPath.cpp
@@ -112,7 +112,7 @@
     // logical treatment of where you would expect the "root" to be.
     Node* context = evaluationContext.node.get();
     if (m_absolute && context->getNodeType() != Node::DOCUMENT_NODE)  {
-        if (context->inDocument())
+        if (context->inShadowIncludingDocument())
             context = context->ownerDocument();
         else
             context = &NodeTraversal::highestAncestorOrSelf(*context);
diff --git a/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp b/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp
index 2f4c21c..ac7b7ace 100644
--- a/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp
+++ b/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp
@@ -837,7 +837,7 @@
     }
 
     // If the parent element is not in document tree, there may be no xmlns attribute; just default to the parent's namespace.
-    if (m_defaultNamespaceURI.isNull() && !parentElement->inDocument())
+    if (m_defaultNamespaceURI.isNull() && !parentElement->inShadowIncludingDocument())
         m_defaultNamespaceURI = parentElement->namespaceURI();
 }
 
@@ -1081,7 +1081,7 @@
 
     // The element's parent may have already been removed from document.
     // Parsing continues in this case, but scripts aren't executed.
-    if (!element->inDocument()) {
+    if (!element->inShadowIncludingDocument()) {
         popCurrentNode();
         return;
     }
diff --git a/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequestProgressEventThrottle.cpp b/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequestProgressEventThrottle.cpp
index 7c9fbcd..1d53b0d 100644
--- a/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequestProgressEventThrottle.cpp
+++ b/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequestProgressEventThrottle.cpp
@@ -61,13 +61,13 @@
     m_total = 0;
 }
 
-RawPtr<Event> XMLHttpRequestProgressEventThrottle::DeferredEvent::take()
+Event* XMLHttpRequestProgressEventThrottle::DeferredEvent::take()
 {
     ASSERT(m_isSet);
 
-    RawPtr<Event> event = ProgressEvent::create(EventTypeNames::progress, m_lengthComputable, m_loaded, m_total);
+    Event* event = ProgressEvent::create(EventTypeNames::progress, m_lengthComputable, m_loaded, m_total);
     clear();
-    return event.release();
+    return event;
 }
 
 XMLHttpRequestProgressEventThrottle::XMLHttpRequestProgressEventThrottle(XMLHttpRequest* target)
@@ -98,7 +98,7 @@
     }
 }
 
-void XMLHttpRequestProgressEventThrottle::dispatchReadyStateChangeEvent(RawPtr<Event> event, DeferredEventAction action)
+void XMLHttpRequestProgressEventThrottle::dispatchReadyStateChangeEvent(Event* event, DeferredEventAction action)
 {
     XMLHttpRequest::State state = m_target->readyState();
     // Given that ResourceDispatcher doesn't deliver an event when suspended,
@@ -124,7 +124,7 @@
     }
 }
 
-void XMLHttpRequestProgressEventThrottle::dispatchProgressProgressEvent(RawPtr<Event> progressEvent)
+void XMLHttpRequestProgressEventThrottle::dispatchProgressProgressEvent(Event* progressEvent)
 {
     XMLHttpRequest::State state = m_target->readyState();
     if (m_target->readyState() == XMLHttpRequest::LOADING && m_hasDispatchedProgressProgressEvent) {
diff --git a/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequestProgressEventThrottle.h b/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequestProgressEventThrottle.h
index fbae73f3..23ceb9c5 100644
--- a/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequestProgressEventThrottle.h
+++ b/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequestProgressEventThrottle.h
@@ -75,7 +75,7 @@
     void dispatchProgressEvent(const AtomicString&, bool lengthComputable, unsigned long long loaded, unsigned long long total);
     // Dispatches the given event after operation about the "progress" event
     // depending on the value of the ProgressEventAction argument.
-    void dispatchReadyStateChangeEvent(RawPtr<Event>, DeferredEventAction);
+    void dispatchReadyStateChangeEvent(Event*, DeferredEventAction);
 
     void suspend();
     void resume();
@@ -89,7 +89,7 @@
 
     // Dispatches a "progress" progress event and usually a readyStateChange
     // event as well.
-    void dispatchProgressProgressEvent(RawPtr<Event>);
+    void dispatchProgressProgressEvent(Event*);
 
     // The main purpose of this class is to throttle the "progress"
     // ProgressEvent dispatching. This class represents such a deferred
@@ -100,7 +100,7 @@
         void set(bool lengthComputable, unsigned long long loaded, unsigned long long total);
         void clear();
         bool isSet() const { return m_isSet; }
-        RawPtr<Event> take();
+        Event* take();
 
     private:
         unsigned long long m_loaded;
diff --git a/third_party/WebKit/Source/devtools/front_end/resources/ServiceWorkersView.js b/third_party/WebKit/Source/devtools/front_end/resources/ServiceWorkersView.js
index 1480638..89806df5 100644
--- a/third_party/WebKit/Source/devtools/front_end/resources/ServiceWorkersView.js
+++ b/third_party/WebKit/Source/devtools/front_end/resources/ServiceWorkersView.js
@@ -314,9 +314,21 @@
         /** @type {!Map<string, !WebInspector.SWVersionWidget>} */
         var versionWidgets = new Map();
 
-        var modesWithVersions = new Set();
+        // Remove all the redundant workers that are older than the
+        // active version.
+        var versions = registration.versions.valuesArray();
+        var activeVersion = versions.find(version => version.mode() === WebInspector.ServiceWorkerVersion.Modes.Active);
+        if (activeVersion) {
+            versions = versions.filter(version => {
+                if (version.mode() == WebInspector.ServiceWorkerVersion.Modes.Redundant)
+                    return version.scriptLastModified > activeVersion.scriptLastModified;
+                return true;
+            });
+        }
+
         var firstMode;
-        for (var version of registration.versions.valuesArray()) {
+        var modesWithVersions = new Set();
+        for (var version of versions) {
             if (version.isStoppedAndRedundant() && !version.errorMessages.length)
                 continue;
             var mode = version.mode();
@@ -329,7 +341,7 @@
                 versionWidget._updateVersion(version);
             else
                 versionWidget = new WebInspector.SWVersionWidget(this._manager, this._registration.scopeURL, version);
-            versionWidget.show(view.element);
+            versionWidget.show(view.element, view.element.firstElementChild);
             versionWidgets.set(version.id, versionWidget);
         }
         for (var id of this._versionWidgets.keys()) {
@@ -347,7 +359,7 @@
             this._tabbedPane.selectTab(this._lastManuallySelectedTab);
             return;
         }
-        if (modesWithVersions.has(WebInspector.ServiceWorkerVersion.Modes.Active)) {
+        if (activeVersion) {
             this._tabbedPane.selectTab(WebInspector.ServiceWorkerVersion.Modes.Active);
             return;
         }
diff --git a/third_party/WebKit/Source/devtools/front_end/timeline/TimelineFlameChart.js b/third_party/WebKit/Source/devtools/front_end/timeline/TimelineFlameChart.js
index e9e4e1b..76b23ac 100644
--- a/third_party/WebKit/Source/devtools/front_end/timeline/TimelineFlameChart.js
+++ b/third_party/WebKit/Source/devtools/front_end/timeline/TimelineFlameChart.js
@@ -304,6 +304,28 @@
         nestingLevel: 1,
         shareHeaderLine: true
     };
+
+    this._interactionsHeaderLevel1 = {
+        padding: 4,
+        height: 17,
+        collapsible: Runtime.experiments.isEnabled("timelineLatencyInfo"),
+        color: WebInspector.themeSupport.patchColor("#222", WebInspector.ThemeSupport.ColorUsage.Foreground),
+        font: this._font,
+        backgroundColor: WebInspector.themeSupport.patchColor("white", WebInspector.ThemeSupport.ColorUsage.Background),
+        nestingLevel: 0,
+        useFirstLineForOverview: true,
+        shareHeaderLine: true
+    };
+
+    this._interactionsHeaderLevel2 = {
+        padding: 4,
+        height: 17,
+        collapsible: true,
+        color: WebInspector.themeSupport.patchColor("#222", WebInspector.ThemeSupport.ColorUsage.Foreground),
+        font: this._font,
+        backgroundColor: WebInspector.themeSupport.patchColor("white", WebInspector.ThemeSupport.ColorUsage.Background),
+        nestingLevel: 1
+    };
 }
 
 WebInspector.TimelineFlameChartDataProvider.InstantEventVisibleDurationMs = 0.001;
@@ -385,8 +407,21 @@
         this._timeSpan = this._model.isEmpty() ?  1000 : this._model.maximumRecordTime() - this._minimumBoundary;
         this._currentLevel = 0;
         this._appendFrameBars(this._frameModel.frames());
+
+        this._appendHeader(WebInspector.UIString("Interactions"), this._interactionsHeaderLevel1);
         this._appendInteractionRecords();
 
+        if (Runtime.experiments.isEnabled("timelineLatencyInfo")) {
+            var asyncEventGroups = WebInspector.TimelineUIUtils.asyncEventGroups();
+            var inputLatencies = this._model.mainThreadAsyncEvents().get(asyncEventGroups.input);
+            if (inputLatencies && inputLatencies.length)
+                this._appendAsyncEventsGroup(asyncEventGroups.input.title, inputLatencies, this._interactionsHeaderLevel2);
+
+            var animations = this._model.mainThreadAsyncEvents().get(asyncEventGroups.animation);
+            if (animations && animations.length)
+                this._appendAsyncEventsGroup(asyncEventGroups.animation.title, animations, this._interactionsHeaderLevel2);
+        }
+
         var threads = this._model.virtualThreads();
         this._appendThreadTimelineData(WebInspector.UIString("Main"), this._model.mainThreadEvents(), this._model.mainThreadAsyncEvents(), true);
         var compositorThreads = threads.filter(thread => thread.name.startsWith("CompositorTileWorker"));
@@ -508,24 +543,23 @@
         var groups = WebInspector.TimelineUIUtils.asyncEventGroups();
         var groupArray = Object.values(groups);
 
-        if (!Runtime.experiments.isEnabled("timelineLatencyInfo")) {
-            groupArray.remove(groups.animation);
-            groupArray.remove(groups.input);
-        }
+        groupArray.remove(groups.animation);
+        groupArray.remove(groups.input);
 
         for (var groupIndex = 0; groupIndex < groupArray.length; ++groupIndex) {
             var group = groupArray[groupIndex];
             var events = asyncEvents.get(group);
             if (events)
-                this._appendAsyncEventsGroup(group.title, events);
+                this._appendAsyncEventsGroup(group.title, events, this._headerLevel1);
         }
     },
 
     /**
      * @param {string} header
      * @param {!Array<!WebInspector.TracingModel.AsyncEvent>} events
+     * @param {!WebInspector.FlameChart.GroupStyle} style
      */
-    _appendAsyncEventsGroup: function(header, events)
+    _appendAsyncEventsGroup: function(header, events, style)
     {
         var lastUsedTimeByLevel = [];
         var groupHeaderAppended = false;
@@ -534,7 +568,7 @@
             if (!this._isVisible(asyncEvent))
                 continue;
             if (!groupHeaderAppended) {
-                this._appendHeader(header, this._headerLevel1);
+                this._appendHeader(header, style);
                 groupHeaderAppended = true;
             }
             var startTime = asyncEvent.startTime;
diff --git a/third_party/WebKit/Source/devtools/front_end/ui_lazy/FlameChart.js b/third_party/WebKit/Source/devtools/front_end/ui_lazy/FlameChart.js
index 5cdacf6..c742725 100644
--- a/third_party/WebKit/Source/devtools/front_end/ui_lazy/FlameChart.js
+++ b/third_party/WebKit/Source/devtools/front_end/ui_lazy/FlameChart.js
@@ -102,6 +102,18 @@
     this._paddingLeft = this._dataProvider.paddingLeft();
     var markerPadding = 2;
     this._markerRadius = this._barHeight / 2 - markerPadding;
+
+    /** @const */
+    this._headerLeftPadding = 6;
+    /** @const */
+    this._arrowSide = 8;
+    /** @const */
+    this._expansionArrowX = this._headerLeftPadding + this._arrowSide / 2;
+    /** @const */
+    this._headerLabelXPadding = 3;
+    /** @const */
+    this._headerLabelYPadding = 2;
+
     this._highlightedMarkerIndex = -1;
     this._highlightedEntryIndex = -1;
     this._selectedEntryIndex = -1;
@@ -137,7 +149,8 @@
  *     color: string,
  *     backgroundColor: string,
  *     nestingLevel: number,
- *     shareHeaderLine: (boolean|undefined)
+ *     shareHeaderLine: (boolean|undefined),
+ *     useFirstLineForOverview: (boolean|undefined)
  * }}
  */
 WebInspector.FlameChart.GroupStyle;
@@ -747,6 +760,11 @@
             return;
         if (this._isDragging)
             return;
+        if (this._coordinatesToGroupIndex(event.offsetX, event.offsetY) >= 0) {
+            this.hideHighlight();
+            this._canvas.style.cursor = "pointer";
+            return;
+        }
         this._updateHighlight();
     },
 
@@ -1114,9 +1132,17 @@
         var groups = this._rawTimelineData.groups || [];
         var group = this._groupOffsets.upperBound(y) - 1;
 
-        if (group >= 0 && group < groups.length && y - this._groupOffsets[group] < groups[group].style.height && !groups[group].style.shareHeaderLine)
-            return group;
-        return -1;
+        if (group < 0 || group >= groups.length || y - this._groupOffsets[group] >= groups[group].style.height)
+            return -1;
+        var context = this._canvas.getContext("2d");
+        context.save();
+        context.font = groups[group].style.font;
+        var right = this._headerLeftPadding + this._labelWidthForGroup(context, groups[group]);
+        context.restore();
+        if (x > right)
+            return -1;
+
+        return group;
     },
 
     /**
@@ -1379,22 +1405,16 @@
             this._drawCollapsedOverviewForGroup(offset + 1, group.startLevel, endLevel);
         });
 
-        var headerLeftPadding = 6;
-        var arrowSide = 8;
-        var expansionArrowX = headerLeftPadding + arrowSide / 2;
-
         context.save();
         forEachGroup((offset, index, group) => {
             context.font = group.style.font;
             if (group.style.collapsible && !group.expanded || group.style.shareHeaderLine) {
-                var vPadding = 2;
-                var hPadding = 3;
-                var width = this._measureWidth(context, group.name) + 1.5 * arrowSide + 2 * hPadding;
-                context.fillStyle = WebInspector.Color.parse(group.style.backgroundColor).setAlpha(0.5).asString(null);
-                context.fillRect(headerLeftPadding - hPadding, offset + vPadding, width, barHeight - 2 * vPadding);
+                var width = this._labelWidthForGroup(context, group);
+                context.fillStyle = WebInspector.Color.parse(group.style.backgroundColor).setAlpha(0.7).asString(null);
+                context.fillRect(this._headerLeftPadding - this._headerLabelXPadding, offset + this._headerLabelYPadding, width, barHeight - 2 * this._headerLabelYPadding);
             }
             context.fillStyle = group.style.color;
-            context.fillText(group.name, Math.floor(expansionArrowX + arrowSide), offset + textBaseHeight);
+            context.fillText(group.name, Math.floor(this._expansionArrowX + this._arrowSide), offset + textBaseHeight);
         });
         context.restore();
 
@@ -1402,7 +1422,7 @@
         context.beginPath();
         forEachGroup((offset, index, group) => {
             if (group.style.collapsible)
-                drawExpansionArrow(expansionArrowX, offset + textBaseHeight - arrowSide / 2, !!group.expanded)
+                drawExpansionArrow.call(this, this._expansionArrowX, offset + textBaseHeight - this._arrowSide / 2, !!group.expanded)
         });
         context.fill();
 
@@ -1425,16 +1445,17 @@
          * @param {number} x
          * @param {number} y
          * @param {boolean} expanded
+         * @this {WebInspector.FlameChart}
          */
         function drawExpansionArrow(x, y, expanded)
         {
-            var arrowHeight = arrowSide * Math.sqrt(3) / 2;
+            var arrowHeight = this._arrowSide * Math.sqrt(3) / 2;
             var arrowCenterOffset = Math.round(arrowHeight / 2);
             context.save();
             context.translate(x, y);
             context.rotate(expanded ? Math.PI / 2 : 0);
-            context.moveTo(-arrowCenterOffset, -arrowSide / 2);
-            context.lineTo(-arrowCenterOffset, arrowSide / 2);
+            context.moveTo(-arrowCenterOffset, -this._arrowSide / 2);
+            context.lineTo(-arrowCenterOffset, this._arrowSide / 2);
             context.lineTo(arrowHeight - arrowCenterOffset, 0);
             context.restore();
         }
@@ -1467,6 +1488,16 @@
     },
 
     /**
+     * @param {!CanvasRenderingContext2D} context
+     * @param {!WebInspector.FlameChart.Group} group
+     * @return {number}
+     */
+    _labelWidthForGroup: function(context, group)
+    {
+       return this._measureWidth(context, group.name) + 1.5 * this._arrowSide + 2 * this._headerLabelXPadding;
+    },
+
+    /**
      * @param {number} y
      * @param {number} startLevel
      * @param {number} endLevel
@@ -1688,9 +1719,10 @@
                 if (parentGroupIsVisible && !style.shareHeaderLine)
                     currentOffset += style.height;
             }
-            this._visibleLevels[level] = visible;
+            var thisLevelIsVisible = visible || groupIndex >= 0 && groups[groupIndex].style.useFirstLineForOverview && level === groups[groupIndex].startLevel;
+            this._visibleLevels[level] = thisLevelIsVisible;
             this._visibleLevelOffsets[level] = currentOffset;
-            if (visible)
+            if (thisLevelIsVisible)
                 currentOffset += this._barHeight;
         }
         if (groupIndex >= 0)
diff --git a/third_party/WebKit/Source/modules/accessibility/AXObject.cpp b/third_party/WebKit/Source/modules/accessibility/AXObject.cpp
index 8f6582be..030a68c 100644
--- a/third_party/WebKit/Source/modules/accessibility/AXObject.cpp
+++ b/third_party/WebKit/Source/modules/accessibility/AXObject.cpp
@@ -1532,7 +1532,7 @@
 
     // If the position is not in the same editable region as this AX object, return -1.
     Node* containerNode = position.deepEquivalent().computeContainerNode();
-    if (!containerNode->containsIncludingShadowDOM(getNode()) && !getNode()->containsIncludingShadowDOM(containerNode))
+    if (!containerNode->isShadowIncludingInclusiveAncestorOf(getNode()) && !getNode()->isShadowIncludingInclusiveAncestorOf(containerNode))
         return -1;
 
     int lineCount = -1;
diff --git a/third_party/WebKit/Source/modules/bluetooth/BluetoothError.cpp b/third_party/WebKit/Source/modules/bluetooth/BluetoothError.cpp
index 220aa29..5c90934b 100644
--- a/third_party/WebKit/Source/modules/bluetooth/BluetoothError.cpp
+++ b/third_party/WebKit/Source/modules/bluetooth/BluetoothError.cpp
@@ -72,7 +72,7 @@
         MAP_ERROR(BLACKLISTED_WRITE, SecurityError, "writeValue() called on blacklisted object marked exclude-writes. https://goo.gl/4NeimX");
         MAP_ERROR(NOT_ALLOWED_TO_ACCESS_SERVICE, SecurityError, "Origin is not allowed to access the service. Remember to add the service to a filter or to optionalServices in requestDevice().");
         MAP_ERROR(REQUEST_DEVICE_WITH_BLACKLISTED_UUID, SecurityError, "requestDevice() called with a filter containing a blacklisted UUID. https://goo.gl/4NeimX");
-        MAP_ERROR(REQUEST_DEVICE_WITH_UNIQUE_ORIGIN, SecurityError, "requestDevice() called from sandboxed or otherwise unique origin.");
+        MAP_ERROR(REQUEST_DEVICE_FROM_CROSS_ORIGIN_IFRAME, SecurityError, "requestDevice() called from cross-origin iframe.");
         MAP_ERROR(REQUEST_DEVICE_WITHOUT_FRAME, SecurityError, "No window to show the requestDevice() dialog.");
 
 #undef MAP_ERROR
diff --git a/third_party/WebKit/Source/modules/canvas2d/CanvasStyle.cpp b/third_party/WebKit/Source/modules/canvas2d/CanvasStyle.cpp
index d7f716a5..ffd38e6 100644
--- a/third_party/WebKit/Source/modules/canvas2d/CanvasStyle.cpp
+++ b/third_party/WebKit/Source/modules/canvas2d/CanvasStyle.cpp
@@ -54,7 +54,7 @@
 
 static Color currentColor(HTMLCanvasElement* canvas)
 {
-    if (!canvas || !canvas->inDocument() || !canvas->inlineStyle())
+    if (!canvas || !canvas->inShadowIncludingDocument() || !canvas->inlineStyle())
         return Color::black;
     Color color = Color::black;
     CSSParser::parseColor(color, canvas->inlineStyle()->getPropertyValue(CSSPropertyColor));
diff --git a/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerGlobalScope.cpp b/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerGlobalScope.cpp
index fc126a0..305805ec 100644
--- a/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerGlobalScope.cpp
+++ b/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerGlobalScope.cpp
@@ -12,14 +12,14 @@
 
 namespace blink {
 
-RawPtr<CompositorWorkerGlobalScope> CompositorWorkerGlobalScope::create(CompositorWorkerThread* thread, PassOwnPtr<WorkerThreadStartupData> startupData, double timeOrigin)
+CompositorWorkerGlobalScope* CompositorWorkerGlobalScope::create(CompositorWorkerThread* thread, PassOwnPtr<WorkerThreadStartupData> startupData, double timeOrigin)
 {
     // Note: startupData is finalized on return. After the relevant parts has been
     // passed along to the created 'context'.
-    RawPtr<CompositorWorkerGlobalScope> context = new CompositorWorkerGlobalScope(startupData->m_scriptURL, startupData->m_userAgent, thread, timeOrigin, startupData->m_starterOriginPrivilegeData.release(), startupData->m_workerClients.release());
+    CompositorWorkerGlobalScope* context = new CompositorWorkerGlobalScope(startupData->m_scriptURL, startupData->m_userAgent, thread, timeOrigin, startupData->m_starterOriginPrivilegeData.release(), startupData->m_workerClients.release());
     context->applyContentSecurityPolicyFromVector(*startupData->m_contentSecurityPolicyHeaders);
     context->setAddressSpace(startupData->m_addressSpace);
-    return context.release();
+    return context;
 }
 
 CompositorWorkerGlobalScope::CompositorWorkerGlobalScope(const KURL& url, const String& userAgent, CompositorWorkerThread* thread, double timeOrigin, PassOwnPtr<SecurityOrigin::PrivilegeData> starterOriginPrivilegeData, RawPtr<WorkerClients> workerClients)
diff --git a/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerGlobalScope.h b/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerGlobalScope.h
index 8f40e97..c53490f5 100644
--- a/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerGlobalScope.h
+++ b/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerGlobalScope.h
@@ -17,7 +17,7 @@
 class CompositorWorkerGlobalScope final : public WorkerGlobalScope {
     DEFINE_WRAPPERTYPEINFO();
 public:
-    static RawPtr<CompositorWorkerGlobalScope> create(CompositorWorkerThread*, PassOwnPtr<WorkerThreadStartupData>, double timeOrigin);
+    static CompositorWorkerGlobalScope* create(CompositorWorkerThread*, PassOwnPtr<WorkerThreadStartupData>, double timeOrigin);
     ~CompositorWorkerGlobalScope() override;
 
     // EventTarget
diff --git a/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerThread.cpp b/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerThread.cpp
index 89a44f1..004e2e6d 100644
--- a/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerThread.cpp
+++ b/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerThread.cpp
@@ -160,7 +160,7 @@
     return CompositorWorkerSharedState::instance().compositorWorkerThread();
 }
 
-RawPtr<WorkerGlobalScope> CompositorWorkerThread::createWorkerGlobalScope(PassOwnPtr<WorkerThreadStartupData> startupData)
+WorkerGlobalScope*CompositorWorkerThread::createWorkerGlobalScope(PassOwnPtr<WorkerThreadStartupData> startupData)
 {
     TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("compositor-worker"), "CompositorWorkerThread::createWorkerGlobalScope");
     return CompositorWorkerGlobalScope::create(this, startupData, m_timeOrigin);
diff --git a/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerThread.h b/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerThread.h
index 4e96a6b..417b0b3 100644
--- a/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerThread.h
+++ b/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerThread.h
@@ -30,7 +30,7 @@
     CompositorWorkerThread(PassRefPtr<WorkerLoaderProxy>, WorkerObjectProxy&, double timeOrigin);
 
     // WorkerThread:
-    RawPtr<WorkerGlobalScope> createWorkerGlobalScope(PassOwnPtr<WorkerThreadStartupData>) override;
+    WorkerGlobalScope* createWorkerGlobalScope(PassOwnPtr<WorkerThreadStartupData>) override;
     WebThreadSupportingGC& backingThread() override;
     void didStartWorkerThread() override { }
     void willStopWorkerThread() override { }
diff --git a/third_party/WebKit/Source/modules/credentialmanager/NavigatorCredentials.cpp b/third_party/WebKit/Source/modules/credentialmanager/NavigatorCredentials.cpp
index 5326cf0f..5a1fcc4f 100644
--- a/third_party/WebKit/Source/modules/credentialmanager/NavigatorCredentials.cpp
+++ b/third_party/WebKit/Source/modules/credentialmanager/NavigatorCredentials.cpp
@@ -17,10 +17,6 @@
 {
 }
 
-NavigatorCredentials::~NavigatorCredentials()
-{
-}
-
 NavigatorCredentials& NavigatorCredentials::from(Navigator& navigator)
 {
     NavigatorCredentials* supplement = static_cast<NavigatorCredentials*>(Supplement<Navigator>::from(navigator, supplementName()));
diff --git a/third_party/WebKit/Source/modules/credentialmanager/NavigatorCredentials.h b/third_party/WebKit/Source/modules/credentialmanager/NavigatorCredentials.h
index bcf9126..f73529c 100644
--- a/third_party/WebKit/Source/modules/credentialmanager/NavigatorCredentials.h
+++ b/third_party/WebKit/Source/modules/credentialmanager/NavigatorCredentials.h
@@ -15,12 +15,10 @@
 class CredentialsContainer;
 class Navigator;
 
-class NavigatorCredentials final : public GarbageCollectedFinalized<NavigatorCredentials>, public Supplement<Navigator>, public DOMWindowProperty {
+class NavigatorCredentials final : public GarbageCollected<NavigatorCredentials>, public Supplement<Navigator>, public DOMWindowProperty {
     USING_GARBAGE_COLLECTED_MIXIN(NavigatorCredentials);
 public:
     static NavigatorCredentials& from(Navigator&);
-    virtual ~NavigatorCredentials();
-
     // NavigatorCredentials.idl
     static CredentialsContainer* credentials(Navigator&);
 
diff --git a/third_party/WebKit/Source/modules/donottrack/NavigatorDoNotTrack.cpp b/third_party/WebKit/Source/modules/donottrack/NavigatorDoNotTrack.cpp
index 9c5921a..a43cf58 100644
--- a/third_party/WebKit/Source/modules/donottrack/NavigatorDoNotTrack.cpp
+++ b/third_party/WebKit/Source/modules/donottrack/NavigatorDoNotTrack.cpp
@@ -41,10 +41,6 @@
 {
 }
 
-NavigatorDoNotTrack::~NavigatorDoNotTrack()
-{
-}
-
 DEFINE_TRACE(NavigatorDoNotTrack)
 {
     Supplement<Navigator>::trace(visitor);
diff --git a/third_party/WebKit/Source/modules/donottrack/NavigatorDoNotTrack.h b/third_party/WebKit/Source/modules/donottrack/NavigatorDoNotTrack.h
index aa45827c..bf4bdb1 100644
--- a/third_party/WebKit/Source/modules/donottrack/NavigatorDoNotTrack.h
+++ b/third_party/WebKit/Source/modules/donottrack/NavigatorDoNotTrack.h
@@ -41,12 +41,10 @@
 class LocalFrame;
 class Navigator;
 
-class NavigatorDoNotTrack final : public GarbageCollectedFinalized<NavigatorDoNotTrack>, public Supplement<Navigator>, public DOMWindowProperty {
+class NavigatorDoNotTrack final : public GarbageCollected<NavigatorDoNotTrack>, public Supplement<Navigator>, public DOMWindowProperty {
     USING_GARBAGE_COLLECTED_MIXIN(NavigatorDoNotTrack);
 public:
     static NavigatorDoNotTrack& from(Navigator&);
-    virtual ~NavigatorDoNotTrack();
-
     static String doNotTrack(Navigator&);
 
     String doNotTrack();
diff --git a/third_party/WebKit/Source/modules/fetch/FetchDataConsumerHandle.h b/third_party/WebKit/Source/modules/fetch/FetchDataConsumerHandle.h
index 948eca4..1179835 100644
--- a/third_party/WebKit/Source/modules/fetch/FetchDataConsumerHandle.h
+++ b/third_party/WebKit/Source/modules/fetch/FetchDataConsumerHandle.h
@@ -62,8 +62,8 @@
     };
 
     // TODO(yhirano): obtainReader() is currently non-virtual override, and
-    // will be changed into virtual override when we can use scoped_ptr /
-    // unique_ptr in both Blink and Chromium.
+    // will be changed into virtual override when we can use unique_ptr in
+    // Blink.
     PassOwnPtr<Reader> obtainReader(Client* client) { return adoptPtr(obtainReaderInternal(client)); }
 
 private:
diff --git a/third_party/WebKit/Source/modules/geolocation/NavigatorGeolocation.cpp b/third_party/WebKit/Source/modules/geolocation/NavigatorGeolocation.cpp
index 1af9561b..c8a706c 100644
--- a/third_party/WebKit/Source/modules/geolocation/NavigatorGeolocation.cpp
+++ b/third_party/WebKit/Source/modules/geolocation/NavigatorGeolocation.cpp
@@ -34,10 +34,6 @@
 {
 }
 
-NavigatorGeolocation::~NavigatorGeolocation()
-{
-}
-
 const char* NavigatorGeolocation::supplementName()
 {
     return "NavigatorGeolocation";
diff --git a/third_party/WebKit/Source/modules/geolocation/NavigatorGeolocation.h b/third_party/WebKit/Source/modules/geolocation/NavigatorGeolocation.h
index 092a927..dec178d 100644
--- a/third_party/WebKit/Source/modules/geolocation/NavigatorGeolocation.h
+++ b/third_party/WebKit/Source/modules/geolocation/NavigatorGeolocation.h
@@ -30,12 +30,10 @@
 class Geolocation;
 class Navigator;
 
-class NavigatorGeolocation final : public GarbageCollectedFinalized<NavigatorGeolocation>, public Supplement<Navigator>, public DOMWindowProperty {
+class NavigatorGeolocation final : public GarbageCollected<NavigatorGeolocation>, public Supplement<Navigator>, public DOMWindowProperty {
     USING_GARBAGE_COLLECTED_MIXIN(NavigatorGeolocation);
 public:
     static NavigatorGeolocation& from(Navigator&);
-    virtual ~NavigatorGeolocation();
-
     static Geolocation* geolocation(Navigator&);
     Geolocation* geolocation();
 
diff --git a/third_party/WebKit/Source/modules/installedapp/NavigatorInstalledApp.h b/third_party/WebKit/Source/modules/installedapp/NavigatorInstalledApp.h
index 38f5db2..ec2dec838 100644
--- a/third_party/WebKit/Source/modules/installedapp/NavigatorInstalledApp.h
+++ b/third_party/WebKit/Source/modules/installedapp/NavigatorInstalledApp.h
@@ -18,7 +18,7 @@
 class ScriptState;
 class InstalledAppController;
 
-class NavigatorInstalledApp final : public GarbageCollectedFinalized<NavigatorInstalledApp>, public Supplement<Navigator>, public DOMWindowProperty {
+class NavigatorInstalledApp final : public GarbageCollected<NavigatorInstalledApp>, public Supplement<Navigator>, public DOMWindowProperty {
     USING_GARBAGE_COLLECTED_MIXIN(NavigatorInstalledApp);
 public:
     static NavigatorInstalledApp* from(Document&);
diff --git a/third_party/WebKit/Source/modules/netinfo/NavigatorNetworkInformation.cpp b/third_party/WebKit/Source/modules/netinfo/NavigatorNetworkInformation.cpp
index 8152df47..7a66532 100644
--- a/third_party/WebKit/Source/modules/netinfo/NavigatorNetworkInformation.cpp
+++ b/third_party/WebKit/Source/modules/netinfo/NavigatorNetworkInformation.cpp
@@ -16,10 +16,6 @@
 {
 }
 
-NavigatorNetworkInformation::~NavigatorNetworkInformation()
-{
-}
-
 NavigatorNetworkInformation& NavigatorNetworkInformation::from(Navigator& navigator)
 {
     NavigatorNetworkInformation* supplement = toNavigatorNetworkInformation(navigator);
diff --git a/third_party/WebKit/Source/modules/netinfo/NavigatorNetworkInformation.h b/third_party/WebKit/Source/modules/netinfo/NavigatorNetworkInformation.h
index 8975023e..53299b5 100644
--- a/third_party/WebKit/Source/modules/netinfo/NavigatorNetworkInformation.h
+++ b/third_party/WebKit/Source/modules/netinfo/NavigatorNetworkInformation.h
@@ -13,14 +13,11 @@
 class Navigator;
 class NetworkInformation;
 
-class NavigatorNetworkInformation final : public GarbageCollectedFinalized<NavigatorNetworkInformation>, public Supplement<Navigator>, public DOMWindowProperty {
+class NavigatorNetworkInformation final : public GarbageCollected<NavigatorNetworkInformation>, public Supplement<Navigator>, public DOMWindowProperty {
     USING_GARBAGE_COLLECTED_MIXIN(NavigatorNetworkInformation);
 public:
     static NavigatorNetworkInformation& from(Navigator&);
     static NavigatorNetworkInformation* toNavigatorNetworkInformation(Navigator&);
-
-    virtual ~NavigatorNetworkInformation();
-
     static NetworkInformation* connection(Navigator&);
 
     DECLARE_VIRTUAL_TRACE();
diff --git a/third_party/WebKit/Source/modules/plugins/DOMMimeTypeArray.h b/third_party/WebKit/Source/modules/plugins/DOMMimeTypeArray.h
index 96cbf81..18350307 100644
--- a/third_party/WebKit/Source/modules/plugins/DOMMimeTypeArray.h
+++ b/third_party/WebKit/Source/modules/plugins/DOMMimeTypeArray.h
@@ -34,7 +34,7 @@
 class LocalFrame;
 class PluginData;
 
-class DOMMimeTypeArray final : public GarbageCollectedFinalized<DOMMimeTypeArray>, public ScriptWrappable, public DOMWindowProperty {
+class DOMMimeTypeArray final : public GarbageCollected<DOMMimeTypeArray>, public ScriptWrappable, public DOMWindowProperty {
     DEFINE_WRAPPERTYPEINFO();
     USING_GARBAGE_COLLECTED_MIXIN(DOMMimeTypeArray);
 public:
diff --git a/third_party/WebKit/Source/modules/plugins/DOMPluginArray.h b/third_party/WebKit/Source/modules/plugins/DOMPluginArray.h
index c26ba65..c4ce6807 100644
--- a/third_party/WebKit/Source/modules/plugins/DOMPluginArray.h
+++ b/third_party/WebKit/Source/modules/plugins/DOMPluginArray.h
@@ -32,7 +32,7 @@
 class LocalFrame;
 class PluginData;
 
-class DOMPluginArray final : public GarbageCollectedFinalized<DOMPluginArray>, public ScriptWrappable, public DOMWindowProperty {
+class DOMPluginArray final : public GarbageCollected<DOMPluginArray>, public ScriptWrappable, public DOMWindowProperty {
     DEFINE_WRAPPERTYPEINFO();
     USING_GARBAGE_COLLECTED_MIXIN(DOMPluginArray);
 public:
diff --git a/third_party/WebKit/Source/modules/plugins/NavigatorPlugins.cpp b/third_party/WebKit/Source/modules/plugins/NavigatorPlugins.cpp
index ca749f4..2ded274 100644
--- a/third_party/WebKit/Source/modules/plugins/NavigatorPlugins.cpp
+++ b/third_party/WebKit/Source/modules/plugins/NavigatorPlugins.cpp
@@ -17,10 +17,6 @@
 {
 }
 
-NavigatorPlugins::~NavigatorPlugins()
-{
-}
-
 // static
 NavigatorPlugins& NavigatorPlugins::from(Navigator& navigator)
 {
diff --git a/third_party/WebKit/Source/modules/plugins/NavigatorPlugins.h b/third_party/WebKit/Source/modules/plugins/NavigatorPlugins.h
index 7d6c54d..a520067a 100644
--- a/third_party/WebKit/Source/modules/plugins/NavigatorPlugins.h
+++ b/third_party/WebKit/Source/modules/plugins/NavigatorPlugins.h
@@ -15,14 +15,12 @@
 class LocalFrame;
 class Navigator;
 
-class NavigatorPlugins final : public GarbageCollectedFinalized<NavigatorPlugins>, public Supplement<Navigator>, public DOMWindowProperty {
+class NavigatorPlugins final : public GarbageCollected<NavigatorPlugins>, public Supplement<Navigator>, public DOMWindowProperty {
     USING_GARBAGE_COLLECTED_MIXIN(NavigatorPlugins);
 public:
     static NavigatorPlugins& from(Navigator&);
     static NavigatorPlugins* toNavigatorPlugins(Navigator&);
 
-    virtual ~NavigatorPlugins();
-
     static DOMPluginArray* plugins(Navigator&);
     static DOMMimeTypeArray* mimeTypes(Navigator&);
     static bool javaEnabled(Navigator&);
diff --git a/third_party/WebKit/Source/modules/presentation/Presentation.h b/third_party/WebKit/Source/modules/presentation/Presentation.h
index 141ca92..de0ea93 100644
--- a/third_party/WebKit/Source/modules/presentation/Presentation.h
+++ b/third_party/WebKit/Source/modules/presentation/Presentation.h
@@ -21,7 +21,7 @@
 //
 // TODO(Oilpan): switch to GarbageCollected<Presentation> once object is unconditionally on the Oilpan heap.
 class Presentation final
-    : public GarbageCollectedFinalized<Presentation>
+    : public GarbageCollected<Presentation>
     , public ScriptWrappable
     , public DOMWindowProperty {
     USING_GARBAGE_COLLECTED_MIXIN(Presentation);
diff --git a/third_party/WebKit/Source/modules/quota/NavigatorStorageQuota.cpp b/third_party/WebKit/Source/modules/quota/NavigatorStorageQuota.cpp
index 6eab87b..a8b3e770 100644
--- a/third_party/WebKit/Source/modules/quota/NavigatorStorageQuota.cpp
+++ b/third_party/WebKit/Source/modules/quota/NavigatorStorageQuota.cpp
@@ -42,10 +42,6 @@
 {
 }
 
-NavigatorStorageQuota::~NavigatorStorageQuota()
-{
-}
-
 const char* NavigatorStorageQuota::supplementName()
 {
     return "NavigatorStorageQuota";
diff --git a/third_party/WebKit/Source/modules/quota/NavigatorStorageQuota.h b/third_party/WebKit/Source/modules/quota/NavigatorStorageQuota.h
index e35e7f1..08956823 100644
--- a/third_party/WebKit/Source/modules/quota/NavigatorStorageQuota.h
+++ b/third_party/WebKit/Source/modules/quota/NavigatorStorageQuota.h
@@ -43,12 +43,10 @@
 class StorageManager;
 class StorageQuota;
 
-class NavigatorStorageQuota final : public GarbageCollectedFinalized<NavigatorStorageQuota>, public Supplement<Navigator>, public DOMWindowProperty {
+class NavigatorStorageQuota final : public GarbageCollected<NavigatorStorageQuota>, public Supplement<Navigator>, public DOMWindowProperty {
     USING_GARBAGE_COLLECTED_MIXIN(NavigatorStorageQuota);
 public:
     static NavigatorStorageQuota& from(Navigator&);
-    virtual ~NavigatorStorageQuota();
-
     static StorageQuota* storageQuota(Navigator&);
     static DeprecatedStorageQuota* webkitTemporaryStorage(Navigator&);
     static DeprecatedStorageQuota* webkitPersistentStorage(Navigator&);
diff --git a/third_party/WebKit/Source/modules/serviceworkers/NavigatorServiceWorker.cpp b/third_party/WebKit/Source/modules/serviceworkers/NavigatorServiceWorker.cpp
index 70ee04f..a7ba1e19 100644
--- a/third_party/WebKit/Source/modules/serviceworkers/NavigatorServiceWorker.cpp
+++ b/third_party/WebKit/Source/modules/serviceworkers/NavigatorServiceWorker.cpp
@@ -17,10 +17,6 @@
 {
 }
 
-NavigatorServiceWorker::~NavigatorServiceWorker()
-{
-}
-
 NavigatorServiceWorker* NavigatorServiceWorker::from(Document& document)
 {
     if (!document.frame() || !document.frame()->domWindow())
diff --git a/third_party/WebKit/Source/modules/serviceworkers/NavigatorServiceWorker.h b/third_party/WebKit/Source/modules/serviceworkers/NavigatorServiceWorker.h
index b9b2a28..ebcb21b 100644
--- a/third_party/WebKit/Source/modules/serviceworkers/NavigatorServiceWorker.h
+++ b/third_party/WebKit/Source/modules/serviceworkers/NavigatorServiceWorker.h
@@ -17,15 +17,12 @@
 class Navigator;
 class ServiceWorkerContainer;
 
-class MODULES_EXPORT NavigatorServiceWorker final : public GarbageCollectedFinalized<NavigatorServiceWorker>, public Supplement<Navigator>, public DOMWindowProperty {
+class MODULES_EXPORT NavigatorServiceWorker final : public GarbageCollected<NavigatorServiceWorker>, public Supplement<Navigator>, public DOMWindowProperty {
     USING_GARBAGE_COLLECTED_MIXIN(NavigatorServiceWorker);
 public:
     static NavigatorServiceWorker* from(Document&);
     static NavigatorServiceWorker& from(Navigator&);
     static NavigatorServiceWorker* toNavigatorServiceWorker(Navigator&);
-
-    virtual ~NavigatorServiceWorker();
-
     static ServiceWorkerContainer* serviceWorker(ExecutionContext*, Navigator&, ExceptionState&);
 
     DECLARE_VIRTUAL_TRACE();
diff --git a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScope.cpp b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScope.cpp
index b0acf10..ca72032 100644
--- a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScope.cpp
+++ b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScope.cpp
@@ -206,7 +206,7 @@
     WorkerGlobalScope::importScripts(urls, exceptionState);
 }
 
-RawPtr<CachedMetadataHandler> ServiceWorkerGlobalScope::createWorkerScriptCachedMetadataHandler(const KURL& scriptURL, const Vector<char>* metaData)
+CachedMetadataHandler* ServiceWorkerGlobalScope::createWorkerScriptCachedMetadataHandler(const KURL& scriptURL, const Vector<char>* metaData)
 {
     return ServiceWorkerScriptCachedMetadataHandler::create(this, scriptURL, metaData);
 }
diff --git a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScope.h b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScope.h
index e074129..a690354 100644
--- a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScope.h
+++ b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScope.h
@@ -97,7 +97,7 @@
 private:
     ServiceWorkerGlobalScope(const KURL&, const String& userAgent, ServiceWorkerThread*, double timeOrigin, PassOwnPtr<SecurityOrigin::PrivilegeData>, RawPtr<WorkerClients>);
     void importScripts(const Vector<String>& urls, ExceptionState&) override;
-    RawPtr<CachedMetadataHandler> createWorkerScriptCachedMetadataHandler(const KURL& scriptURL, const Vector<char>* metaData) override;
+    CachedMetadataHandler* createWorkerScriptCachedMetadataHandler(const KURL& scriptURL, const Vector<char>* metaData) override;
     void logExceptionToConsole(const String& errorMessage, int scriptId, const String& sourceURL, int lineNumber, int columnNumber, PassRefPtr<ScriptCallStack>) override;
     void scriptLoaded(size_t scriptSize, size_t cachedMetadataSize) override;
 
diff --git a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerThread.cpp b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerThread.cpp
index ffd253c..e84a426 100644
--- a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerThread.cpp
+++ b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerThread.cpp
@@ -49,7 +49,7 @@
 {
 }
 
-RawPtr<WorkerGlobalScope> ServiceWorkerThread::createWorkerGlobalScope(PassOwnPtr<WorkerThreadStartupData> startupData)
+WorkerGlobalScope* ServiceWorkerThread::createWorkerGlobalScope(PassOwnPtr<WorkerThreadStartupData> startupData)
 {
     return ServiceWorkerGlobalScope::create(this, startupData);
 }
diff --git a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerThread.h b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerThread.h
index 6167e8f..a39b429d 100644
--- a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerThread.h
+++ b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerThread.h
@@ -44,7 +44,7 @@
     ~ServiceWorkerThread() override;
 
 protected:
-    RawPtr<WorkerGlobalScope> createWorkerGlobalScope(PassOwnPtr<WorkerThreadStartupData>) override;
+    WorkerGlobalScope* createWorkerGlobalScope(PassOwnPtr<WorkerThreadStartupData>) override;
     WebThreadSupportingGC& backingThread() override;
 
 private:
diff --git a/third_party/WebKit/Source/modules/speech/testing/PlatformSpeechSynthesizerMock.cpp b/third_party/WebKit/Source/modules/speech/testing/PlatformSpeechSynthesizerMock.cpp
index 956b860..6722528 100644
--- a/third_party/WebKit/Source/modules/speech/testing/PlatformSpeechSynthesizerMock.cpp
+++ b/third_party/WebKit/Source/modules/speech/testing/PlatformSpeechSynthesizerMock.cpp
@@ -121,11 +121,17 @@
 
 void PlatformSpeechSynthesizerMock::pause()
 {
+    if (!m_currentUtterance)
+        return;
+
     client()->didPauseSpeaking(m_currentUtterance);
 }
 
 void PlatformSpeechSynthesizerMock::resume()
 {
+    if (!m_currentUtterance)
+        return;
+
     client()->didResumeSpeaking(m_currentUtterance);
 }
 
diff --git a/third_party/WebKit/Source/modules/storage/Storage.cpp b/third_party/WebKit/Source/modules/storage/Storage.cpp
index bafd2f0..06bb4ecb 100644
--- a/third_party/WebKit/Source/modules/storage/Storage.cpp
+++ b/third_party/WebKit/Source/modules/storage/Storage.cpp
@@ -45,10 +45,6 @@
     ASSERT(m_storageArea);
 }
 
-Storage::~Storage()
-{
-}
-
 String Storage::anonymousIndexedGetter(unsigned index, ExceptionState& exceptionState)
 {
     return anonymousNamedGetter(AtomicString::number(index), exceptionState);
diff --git a/third_party/WebKit/Source/modules/storage/Storage.h b/third_party/WebKit/Source/modules/storage/Storage.h
index 5911fc6d..b0d3e0f 100644
--- a/third_party/WebKit/Source/modules/storage/Storage.h
+++ b/third_party/WebKit/Source/modules/storage/Storage.h
@@ -39,13 +39,11 @@
 class ExceptionState;
 class LocalFrame;
 
-class Storage final : public GarbageCollectedFinalized<Storage>, public ScriptWrappable, public DOMWindowProperty {
+class Storage final : public GarbageCollected<Storage>, public ScriptWrappable, public DOMWindowProperty {
     DEFINE_WRAPPERTYPEINFO();
     USING_GARBAGE_COLLECTED_MIXIN(Storage);
 public:
     static Storage* create(LocalFrame*, StorageArea*);
-    virtual ~Storage();
-
     unsigned length(ExceptionState& ec) const { return m_storageArea->length(ec, m_frame); }
     String key(unsigned index, ExceptionState& ec) const { return m_storageArea->key(index, ec, m_frame); }
     String getItem(const String& key, ExceptionState& ec) const { return m_storageArea->getItem(key, ec, m_frame); }
diff --git a/third_party/WebKit/Source/modules/vr/NavigatorVRDevice.cpp b/third_party/WebKit/Source/modules/vr/NavigatorVRDevice.cpp
index dfad15c..aad047a6 100644
--- a/third_party/WebKit/Source/modules/vr/NavigatorVRDevice.cpp
+++ b/third_party/WebKit/Source/modules/vr/NavigatorVRDevice.cpp
@@ -85,10 +85,6 @@
     m_hardwareUnits = new VRHardwareUnitCollection(this);
 }
 
-NavigatorVRDevice::~NavigatorVRDevice()
-{
-}
-
 const char* NavigatorVRDevice::supplementName()
 {
     return "NavigatorVRDevice";
diff --git a/third_party/WebKit/Source/modules/vr/NavigatorVRDevice.h b/third_party/WebKit/Source/modules/vr/NavigatorVRDevice.h
index a20e1fd..e1971cb 100644
--- a/third_party/WebKit/Source/modules/vr/NavigatorVRDevice.h
+++ b/third_party/WebKit/Source/modules/vr/NavigatorVRDevice.h
@@ -22,14 +22,12 @@
 class VRController;
 class VRHardwareUnitCollection;
 
-class MODULES_EXPORT NavigatorVRDevice final : public GarbageCollectedFinalized<NavigatorVRDevice>, public Supplement<Navigator>, public DOMWindowProperty {
+class MODULES_EXPORT NavigatorVRDevice final : public GarbageCollected<NavigatorVRDevice>, public Supplement<Navigator>, public DOMWindowProperty {
     USING_GARBAGE_COLLECTED_MIXIN(NavigatorVRDevice);
     WTF_MAKE_NONCOPYABLE(NavigatorVRDevice);
 public:
     static NavigatorVRDevice* from(Document&);
     static NavigatorVRDevice& from(Navigator&);
-    virtual ~NavigatorVRDevice();
-
     static ScriptPromise getVRDevices(ScriptState*, Navigator&);
     ScriptPromise getVRDevices(ScriptState*);
 
diff --git a/third_party/WebKit/Source/modules/webmidi/NavigatorWebMIDI.cpp b/third_party/WebKit/Source/modules/webmidi/NavigatorWebMIDI.cpp
index 901973b..d27477f3 100644
--- a/third_party/WebKit/Source/modules/webmidi/NavigatorWebMIDI.cpp
+++ b/third_party/WebKit/Source/modules/webmidi/NavigatorWebMIDI.cpp
@@ -47,10 +47,6 @@
 {
 }
 
-NavigatorWebMIDI::~NavigatorWebMIDI()
-{
-}
-
 DEFINE_TRACE(NavigatorWebMIDI)
 {
     Supplement<Navigator>::trace(visitor);
diff --git a/third_party/WebKit/Source/modules/webmidi/NavigatorWebMIDI.h b/third_party/WebKit/Source/modules/webmidi/NavigatorWebMIDI.h
index 152c65a1..0ce434d 100644
--- a/third_party/WebKit/Source/modules/webmidi/NavigatorWebMIDI.h
+++ b/third_party/WebKit/Source/modules/webmidi/NavigatorWebMIDI.h
@@ -41,12 +41,10 @@
 
 class Navigator;
 
-class NavigatorWebMIDI final : public GarbageCollectedFinalized<NavigatorWebMIDI>, public Supplement<Navigator>, public DOMWindowProperty {
+class NavigatorWebMIDI final : public GarbageCollected<NavigatorWebMIDI>, public Supplement<Navigator>, public DOMWindowProperty {
     USING_GARBAGE_COLLECTED_MIXIN(NavigatorWebMIDI);
 public:
     static NavigatorWebMIDI& from(Navigator&);
-    virtual ~NavigatorWebMIDI();
-
     static ScriptPromise requestMIDIAccess(ScriptState*, Navigator&, const MIDIOptions&);
     ScriptPromise requestMIDIAccess(ScriptState*, const MIDIOptions&);
 
diff --git a/third_party/WebKit/Source/platform/BUILD.gn b/third_party/WebKit/Source/platform/BUILD.gn
index 5bba9f7..c31a0d8 100644
--- a/third_party/WebKit/Source/platform/BUILD.gn
+++ b/third_party/WebKit/Source/platform/BUILD.gn
@@ -164,8 +164,8 @@
 
 executable("character_data_generator") {
   sources = [
-    "fonts/CharacterPropertyDataGenerator.cpp",
-    "fonts/CharacterPropertyDataGenerator.h",
+    "text/CharacterPropertyDataGenerator.cpp",
+    "text/CharacterPropertyDataGenerator.h",
   ]
   configs += [ "//third_party/WebKit/Source:config" ]
   deps = [
diff --git a/third_party/WebKit/Source/platform/EventTracer.cpp b/third_party/WebKit/Source/platform/EventTracer.cpp
index 94015e14..6e6b386 100644
--- a/third_party/WebKit/Source/platform/EventTracer.cpp
+++ b/third_party/WebKit/Source/platform/EventTracer.cpp
@@ -76,7 +76,7 @@
     PassOwnPtr<TracedValue> tracedValue2,
     unsigned flags)
 {
-    scoped_ptr<base::trace_event::ConvertableToTraceFormat> convertables[2];
+    std::unique_ptr<base::trace_event::ConvertableToTraceFormat> convertables[2];
     ASSERT(numArgs <= 2);
     // We move m_tracedValues from TracedValues for thread safety.
     // https://crbug.com/478149
@@ -98,7 +98,7 @@
 TraceEvent::TraceEventHandle EventTracer::addTraceEvent(char phase, const unsigned char* categoryEnabledFlag,
     const char* name, const char* scope, unsigned long long id, unsigned long long bindId, double timestamp,
     int numArgs, const char** argNames, const unsigned char* argTypes, const unsigned long long* argValues,
-    scoped_ptr<base::trace_event::ConvertableToTraceFormat>* convertables, unsigned flags)
+    std::unique_ptr<base::trace_event::ConvertableToTraceFormat>* convertables, unsigned flags)
 {
     base::TimeTicks timestampTimeTicks = base::TimeTicks() + base::TimeDelta::FromSecondsD(timestamp);
     base::trace_event::TraceEventHandle handle = TRACE_EVENT_API_ADD_TRACE_EVENT_WITH_THREAD_ID_AND_TIMESTAMP(phase, categoryEnabledFlag, name, scope, id, bindId, base::PlatformThread::CurrentId(), timestampTimeTicks, numArgs, argNames, argTypes, argValues, convertables, flags);
diff --git a/third_party/WebKit/Source/platform/EventTracer.h b/third_party/WebKit/Source/platform/EventTracer.h
index fe589b2..8483dc01e 100644
--- a/third_party/WebKit/Source/platform/EventTracer.h
+++ b/third_party/WebKit/Source/platform/EventTracer.h
@@ -31,13 +31,13 @@
 #ifndef EventTracer_h
 #define EventTracer_h
 
-#include "base/memory/scoped_ptr.h"
 #include "platform/PlatformExport.h"
 #include "wtf/Allocator.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/RefCounted.h"
 #include "wtf/text/WTFString.h"
 
+#include <memory>
 #include <stdint.h>
 
 namespace base {
@@ -109,7 +109,7 @@
         const char* argNames[],
         const unsigned char argTypes[],
         const unsigned long long argValues[],
-        scoped_ptr<base::trace_event::ConvertableToTraceFormat>* convertables,
+        std::unique_ptr<base::trace_event::ConvertableToTraceFormat>* convertables,
         unsigned flags);
 };
 
diff --git a/third_party/WebKit/Source/platform/PurgeableVector.cpp b/third_party/WebKit/Source/platform/PurgeableVector.cpp
index 13b4d47..f8446e43b 100644
--- a/third_party/WebKit/Source/platform/PurgeableVector.cpp
+++ b/third_party/WebKit/Source/platform/PurgeableVector.cpp
@@ -235,7 +235,7 @@
     if (allocationStrategy == UseExponentialGrowth)
         capacity = adjustPurgeableCapacity(capacity);
 
-    scoped_ptr<base::DiscardableMemory> discardable =
+    std::unique_ptr<base::DiscardableMemory> discardable =
         base::DiscardableMemoryAllocator::GetInstance()->AllocateLockedDiscardableMemory(capacity);
     ASSERT(discardable);
 
diff --git a/third_party/WebKit/Source/platform/PurgeableVector.h b/third_party/WebKit/Source/platform/PurgeableVector.h
index 6cbaec5..fd8b1e7 100644
--- a/third_party/WebKit/Source/platform/PurgeableVector.h
+++ b/third_party/WebKit/Source/platform/PurgeableVector.h
@@ -31,12 +31,13 @@
 #ifndef PurgeableVector_h
 #define PurgeableVector_h
 
-#include "base/memory/scoped_ptr.h"
 #include "platform/PlatformExport.h"
 #include "wtf/Forward.h"
 #include "wtf/Noncopyable.h"
 #include "wtf/Vector.h"
 
+#include <memory>
+
 namespace base {
 class DiscardableMemory;
 }
@@ -119,7 +120,7 @@
     // Note that there can't be data both in |m_vector| and
     // |m_discardable|, i.e. only one of them is used at a given time.
     Vector<char> m_vector;
-    scoped_ptr<base::DiscardableMemory> m_discardable;
+    std::unique_ptr<base::DiscardableMemory> m_discardable;
     size_t m_discardableCapacity;
     size_t m_discardableSize;
     bool m_isPurgeable;
diff --git a/third_party/WebKit/Source/platform/TracedValue.h b/third_party/WebKit/Source/platform/TracedValue.h
index bd93221f8..2423700ac 100644
--- a/third_party/WebKit/Source/platform/TracedValue.h
+++ b/third_party/WebKit/Source/platform/TracedValue.h
@@ -51,7 +51,7 @@
 
     // This will be moved (and become null) when TracedValue is passed to
     // EventTracer::addTraceEvent().
-    scoped_ptr<base::trace_event::TracedValue> m_tracedValue;
+    std::unique_ptr<base::trace_event::TracedValue> m_tracedValue;
 
     friend class EventTracer;
 };
diff --git a/third_party/WebKit/Source/platform/TracedValueTest.cpp b/third_party/WebKit/Source/platform/TracedValueTest.cpp
index 66363ab..22e6d7c7 100644
--- a/third_party/WebKit/Source/platform/TracedValueTest.cpp
+++ b/third_party/WebKit/Source/platform/TracedValueTest.cpp
@@ -10,7 +10,7 @@
 
 namespace blink {
 
-scoped_ptr<base::Value> parseTracedValue(PassOwnPtr<TracedValue> value)
+std::unique_ptr<base::Value> parseTracedValue(PassOwnPtr<TracedValue> value)
 {
     base::JSONReader reader;
     CString utf8 = value->toString().utf8();
@@ -25,7 +25,7 @@
     value->setBoolean("bool", true);
     value->setString("string", "string");
 
-    scoped_ptr<base::Value> parsed = parseTracedValue(value.release());
+    std::unique_ptr<base::Value> parsed = parseTracedValue(value.release());
     base::DictionaryValue* dictionary;
     ASSERT_TRUE(parsed->GetAsDictionary(&dictionary));
     int intValue;
@@ -61,7 +61,7 @@
     value->endArray();
     value->setString("s0", "foo");
 
-    scoped_ptr<base::Value> parsed = parseTracedValue(value.release());
+    std::unique_ptr<base::Value> parsed = parseTracedValue(value.release());
     base::DictionaryValue* dictionary;
     ASSERT_TRUE(parsed->GetAsDictionary(&dictionary));
     int i0;
@@ -109,7 +109,7 @@
     value->setString("s3\\", "value3");
     value->setString("\"s4\"", "value4");
 
-    scoped_ptr<base::Value> parsed = parseTracedValue(value.release());
+    std::unique_ptr<base::Value> parsed = parseTracedValue(value.release());
     base::DictionaryValue* dictionary;
     ASSERT_TRUE(parsed->GetAsDictionary(&dictionary));
     std::string s0;
diff --git a/third_party/WebKit/Source/platform/animation/CompositorAnimation.cpp b/third_party/WebKit/Source/platform/animation/CompositorAnimation.cpp
index 5dbc2a2..7ffd475 100644
--- a/third_party/WebKit/Source/platform/animation/CompositorAnimation.cpp
+++ b/third_party/WebKit/Source/platform/animation/CompositorAnimation.cpp
@@ -29,7 +29,7 @@
         groupId = AnimationIdProvider::NextGroupId();
 
     CompositorAnimationCurve::AnimationCurveType curveType = webCurve.type();
-    scoped_ptr<cc::AnimationCurve> curve;
+    std::unique_ptr<cc::AnimationCurve> curve;
     switch (curveType) {
     case CompositorAnimationCurve::AnimationCurveTypeFloat: {
         const blink::CompositorFloatAnimationCurve* floatCurve = static_cast<const blink::CompositorFloatAnimationCurve*>(&webCurve);
@@ -195,7 +195,7 @@
     }
 }
 
-scoped_ptr<cc::Animation> CompositorAnimation::passAnimation()
+std::unique_ptr<cc::Animation> CompositorAnimation::passAnimation()
 {
     m_animation->set_needs_synchronized_start_time(true);
     return std::move(m_animation);
diff --git a/third_party/WebKit/Source/platform/animation/CompositorAnimation.h b/third_party/WebKit/Source/platform/animation/CompositorAnimation.h
index 17a70cb..644567e 100644
--- a/third_party/WebKit/Source/platform/animation/CompositorAnimation.h
+++ b/third_party/WebKit/Source/platform/animation/CompositorAnimation.h
@@ -5,11 +5,12 @@
 #ifndef CompositorAnimation_h
 #define CompositorAnimation_h
 
-#include "base/memory/scoped_ptr.h"
 #include "platform/PlatformExport.h"
 #include "platform/animation/CompositorTargetProperty.h"
 #include "wtf/Noncopyable.h"
 
+#include <memory>
+
 namespace cc {
 class Animation;
 }
@@ -69,13 +70,13 @@
     virtual double iterationStart() const;
     virtual void setIterationStart(double);
 
-    scoped_ptr<cc::Animation> passAnimation();
+    std::unique_ptr<cc::Animation> passAnimation();
 
 protected:
     CompositorAnimation();
 
 private:
-    scoped_ptr<cc::Animation> m_animation;
+    std::unique_ptr<cc::Animation> m_animation;
 };
 
 } // namespace blink
diff --git a/third_party/WebKit/Source/platform/animation/CompositorAnimationCurve.cpp b/third_party/WebKit/Source/platform/animation/CompositorAnimationCurve.cpp
index 7078871..59d64b1f 100644
--- a/third_party/WebKit/Source/platform/animation/CompositorAnimationCurve.cpp
+++ b/third_party/WebKit/Source/platform/animation/CompositorAnimationCurve.cpp
@@ -8,7 +8,7 @@
 
 namespace blink {
 
-scoped_ptr<cc::TimingFunction> CompositorAnimationCurve::createTimingFunction(TimingFunctionType type)
+std::unique_ptr<cc::TimingFunction> CompositorAnimationCurve::createTimingFunction(TimingFunctionType type)
 {
     switch (type) {
     case blink::CompositorAnimationCurve::TimingFunctionTypeEase:
diff --git a/third_party/WebKit/Source/platform/animation/CompositorAnimationCurve.h b/third_party/WebKit/Source/platform/animation/CompositorAnimationCurve.h
index 3d701ba..3f3285d4 100644
--- a/third_party/WebKit/Source/platform/animation/CompositorAnimationCurve.h
+++ b/third_party/WebKit/Source/platform/animation/CompositorAnimationCurve.h
@@ -5,9 +5,10 @@
 #ifndef CompositorAnimationCurve_h
 #define CompositorAnimationCurve_h
 
-#include "base/memory/scoped_ptr.h"
 #include "platform/PlatformExport.h"
 
+#include <memory>
+
 namespace cc {
 class TimingFunction;
 }
@@ -36,7 +37,7 @@
     virtual AnimationCurveType type() const = 0;
 
 protected:
-    static scoped_ptr<cc::TimingFunction> createTimingFunction(TimingFunctionType);
+    static std::unique_ptr<cc::TimingFunction> createTimingFunction(TimingFunctionType);
 };
 
 } // namespace blink
diff --git a/third_party/WebKit/Source/platform/animation/CompositorAnimationDelegate.h b/third_party/WebKit/Source/platform/animation/CompositorAnimationDelegate.h
index 6fe3150..71a1a17 100644
--- a/third_party/WebKit/Source/platform/animation/CompositorAnimationDelegate.h
+++ b/third_party/WebKit/Source/platform/animation/CompositorAnimationDelegate.h
@@ -5,10 +5,11 @@
 #ifndef CompositorAnimationDelegate_h
 #define CompositorAnimationDelegate_h
 
-#include "base/memory/scoped_ptr.h"
 #include "cc/animation/animation_curve.h"
 #include "platform/PlatformExport.h"
 
+#include <memory>
+
 namespace blink {
 
 class PLATFORM_EXPORT CompositorAnimationDelegate {
@@ -25,7 +26,7 @@
     virtual void notifyAnimationTakeover(
         double monotonicTime,
         double animationStartTime,
-        scoped_ptr<cc::AnimationCurve> curve) { }
+        std::unique_ptr<cc::AnimationCurve> curve) { }
 };
 
 } // namespace blink
diff --git a/third_party/WebKit/Source/platform/animation/CompositorAnimationPlayer.cpp b/third_party/WebKit/Source/platform/animation/CompositorAnimationPlayer.cpp
index 819727c..f3abbad 100644
--- a/third_party/WebKit/Source/platform/animation/CompositorAnimationPlayer.cpp
+++ b/third_party/WebKit/Source/platform/animation/CompositorAnimationPlayer.cpp
@@ -105,7 +105,7 @@
     base::TimeTicks monotonicTime,
     cc::TargetProperty::Type,
     double animationStartTime,
-    scoped_ptr<cc::AnimationCurve> curve)
+    std::unique_ptr<cc::AnimationCurve> curve)
 {
     if (m_delegate) {
         m_delegate->notifyAnimationTakeover(
diff --git a/third_party/WebKit/Source/platform/animation/CompositorAnimationPlayer.h b/third_party/WebKit/Source/platform/animation/CompositorAnimationPlayer.h
index 1a92251..62d63d2 100644
--- a/third_party/WebKit/Source/platform/animation/CompositorAnimationPlayer.h
+++ b/third_party/WebKit/Source/platform/animation/CompositorAnimationPlayer.h
@@ -6,7 +6,6 @@
 #define CompositorAnimationPlayer_h
 
 #include "base/memory/ref_counted.h"
-#include "base/memory/scoped_ptr.h"
 #include "cc/animation/animation.h"
 #include "cc/animation/animation_curve.h"
 #include "cc/animation/animation_delegate.h"
@@ -14,6 +13,8 @@
 #include "platform/PlatformExport.h"
 #include "wtf/Noncopyable.h"
 
+#include <memory>
+
 namespace blink {
 
 class CompositorAnimation;
@@ -49,7 +50,7 @@
     void NotifyAnimationStarted(base::TimeTicks monotonicTime, cc::TargetProperty::Type, int group) override;
     void NotifyAnimationFinished(base::TimeTicks monotonicTime, cc::TargetProperty::Type, int group) override;
     void NotifyAnimationAborted(base::TimeTicks monotonicTime, cc::TargetProperty::Type, int group) override;
-    void NotifyAnimationTakeover(base::TimeTicks monotonicTime, cc::TargetProperty::Type, double animationStartTime, scoped_ptr<cc::AnimationCurve>) override;
+    void NotifyAnimationTakeover(base::TimeTicks monotonicTime, cc::TargetProperty::Type, double animationStartTime, std::unique_ptr<cc::AnimationCurve>) override;
 
     scoped_refptr<cc::AnimationPlayer> m_animationPlayer;
     CompositorAnimationDelegate* m_delegate;
diff --git a/third_party/WebKit/Source/platform/animation/CompositorAnimationPlayerTest.cpp b/third_party/WebKit/Source/platform/animation/CompositorAnimationPlayerTest.cpp
index d0d3db1..c37291ef 100644
--- a/third_party/WebKit/Source/platform/animation/CompositorAnimationPlayerTest.cpp
+++ b/third_party/WebKit/Source/platform/animation/CompositorAnimationPlayerTest.cpp
@@ -4,7 +4,6 @@
 
 #include "platform/animation/CompositorAnimationPlayer.h"
 
-#include "base/memory/scoped_ptr.h"
 #include "base/time/time.h"
 #include "platform/animation/CompositorAnimationDelegate.h"
 #include "platform/animation/CompositorAnimationPlayerClient.h"
@@ -12,6 +11,8 @@
 #include "platform/animation/CompositorTargetProperty.h"
 #include "platform/testing/CompositorTest.h"
 
+#include <memory>
+
 namespace blink {
 
 class CompositorAnimationDelegateForTesting : public CompositorAnimationDelegate {
@@ -43,7 +44,7 @@
         return m_player.get();
     }
 
-    scoped_ptr<CompositorAnimationPlayer> m_player;
+    std::unique_ptr<CompositorAnimationPlayer> m_player;
 };
 
 class CompositorAnimationPlayerTest : public CompositorTest {
@@ -53,9 +54,9 @@
 // doesn't forward the finish notification.
 TEST_F(CompositorAnimationPlayerTest, NullDelegate)
 {
-    scoped_ptr<CompositorAnimationDelegateForTesting> delegate(new CompositorAnimationDelegateForTesting);
+    std::unique_ptr<CompositorAnimationDelegateForTesting> delegate(new CompositorAnimationDelegateForTesting);
 
-    scoped_ptr<CompositorAnimationPlayer> player(new CompositorAnimationPlayer);
+    std::unique_ptr<CompositorAnimationPlayer> player(new CompositorAnimationPlayer);
     cc::AnimationPlayer* ccPlayer = player->animationPlayer();
 
     player->setAnimationDelegate(delegate.get());
@@ -73,9 +74,9 @@
 
 TEST_F(CompositorAnimationPlayerTest, NotifyFromCCAfterCompositorPlayerDeletion)
 {
-    scoped_ptr<CompositorAnimationDelegateForTesting> delegate(new CompositorAnimationDelegateForTesting);
+    std::unique_ptr<CompositorAnimationDelegateForTesting> delegate(new CompositorAnimationDelegateForTesting);
 
-    scoped_ptr<CompositorAnimationPlayer> player(new CompositorAnimationPlayer);
+    std::unique_ptr<CompositorAnimationPlayer> player(new CompositorAnimationPlayer);
     scoped_refptr<cc::AnimationPlayer> ccPlayer = player->animationPlayer();
 
     player->setAnimationDelegate(delegate.get());
@@ -91,8 +92,8 @@
 
 TEST_F(CompositorAnimationPlayerTest, CompositorPlayerDeletionDetachesFromCCTimeline)
 {
-    scoped_ptr<CompositorAnimationTimeline> timeline(new CompositorAnimationTimeline);
-    scoped_ptr<CompositorAnimationPlayerTestClient> client(new CompositorAnimationPlayerTestClient);
+    std::unique_ptr<CompositorAnimationTimeline> timeline(new CompositorAnimationTimeline);
+    std::unique_ptr<CompositorAnimationPlayerTestClient> client(new CompositorAnimationPlayerTestClient);
 
     scoped_refptr<cc::AnimationTimeline> ccTimeline = timeline->animationTimeline();
     scoped_refptr<cc::AnimationPlayer> ccPlayer = client->m_player->animationPlayer();
diff --git a/third_party/WebKit/Source/platform/animation/CompositorAnimationTest.cpp b/third_party/WebKit/Source/platform/animation/CompositorAnimationTest.cpp
index 7685ccf..401f9ff 100644
--- a/third_party/WebKit/Source/platform/animation/CompositorAnimationTest.cpp
+++ b/third_party/WebKit/Source/platform/animation/CompositorAnimationTest.cpp
@@ -11,8 +11,8 @@
 
 TEST(WebCompositorAnimationTest, DefaultSettings)
 {
-    scoped_ptr<CompositorAnimationCurve> curve(new CompositorFloatAnimationCurve());
-    scoped_ptr<CompositorAnimation> animation(new CompositorAnimation(
+    std::unique_ptr<CompositorAnimationCurve> curve(new CompositorFloatAnimationCurve());
+    std::unique_ptr<CompositorAnimation> animation(new CompositorAnimation(
         *curve, CompositorTargetProperty::OPACITY, 1, 0));
 
     // Ensure that the defaults are correct.
@@ -24,8 +24,8 @@
 
 TEST(WebCompositorAnimationTest, ModifiedSettings)
 {
-    scoped_ptr<CompositorFloatAnimationCurve> curve(new CompositorFloatAnimationCurve());
-    scoped_ptr<CompositorAnimation> animation(new CompositorAnimation(
+    std::unique_ptr<CompositorFloatAnimationCurve> curve(new CompositorFloatAnimationCurve());
+    std::unique_ptr<CompositorAnimation> animation(new CompositorAnimation(
         *curve, CompositorTargetProperty::OPACITY, 1, 0));
     animation->setIterations(2);
     animation->setStartTime(2);
diff --git a/third_party/WebKit/Source/platform/animation/CompositorAnimationTimeline.h b/third_party/WebKit/Source/platform/animation/CompositorAnimationTimeline.h
index ea02f01..1d9f066 100644
--- a/third_party/WebKit/Source/platform/animation/CompositorAnimationTimeline.h
+++ b/third_party/WebKit/Source/platform/animation/CompositorAnimationTimeline.h
@@ -6,11 +6,12 @@
 #define CompositorAnimationTimeline_h
 
 #include "base/memory/ref_counted.h"
-#include "base/memory/scoped_ptr.h"
 #include "cc/animation/animation_timeline.h"
 #include "platform/PlatformExport.h"
 #include "wtf/Noncopyable.h"
 
+#include <memory>
+
 namespace blink {
 
 class CompositorAnimationPlayerClient;
diff --git a/third_party/WebKit/Source/platform/animation/CompositorFilterAnimationCurve.cpp b/third_party/WebKit/Source/platform/animation/CompositorFilterAnimationCurve.cpp
index 4341584..9548e5b 100644
--- a/third_party/WebKit/Source/platform/animation/CompositorFilterAnimationCurve.cpp
+++ b/third_party/WebKit/Source/platform/animation/CompositorFilterAnimationCurve.cpp
@@ -71,7 +71,7 @@
     m_curve->SetTimingFunction(cc::StepsTimingFunction::Create(numberOfSteps, stepsStartOffset));
 }
 
-scoped_ptr<cc::AnimationCurve> CompositorFilterAnimationCurve::cloneToAnimationCurve() const
+std::unique_ptr<cc::AnimationCurve> CompositorFilterAnimationCurve::cloneToAnimationCurve() const
 {
     return m_curve->Clone();
 }
diff --git a/third_party/WebKit/Source/platform/animation/CompositorFilterAnimationCurve.h b/third_party/WebKit/Source/platform/animation/CompositorFilterAnimationCurve.h
index a5eae419..ef9ff92 100644
--- a/third_party/WebKit/Source/platform/animation/CompositorFilterAnimationCurve.h
+++ b/third_party/WebKit/Source/platform/animation/CompositorFilterAnimationCurve.h
@@ -5,12 +5,13 @@
 #ifndef CompositorFilterAnimationCurve_h
 #define CompositorFilterAnimationCurve_h
 
-#include "base/memory/scoped_ptr.h"
 #include "platform/PlatformExport.h"
 #include "platform/animation/CompositorAnimationCurve.h"
 #include "platform/animation/CompositorFilterKeyframe.h"
 #include "wtf/Noncopyable.h"
 
+#include <memory>
+
 namespace cc {
 class AnimationCurve;
 class KeyframedFilterAnimationCurve;
@@ -44,10 +45,10 @@
     // blink::CompositorAnimationCurve implementation.
     AnimationCurveType type() const override;
 
-    scoped_ptr<cc::AnimationCurve> cloneToAnimationCurve() const;
+    std::unique_ptr<cc::AnimationCurve> cloneToAnimationCurve() const;
 
 private:
-    scoped_ptr<cc::KeyframedFilterAnimationCurve> m_curve;
+    std::unique_ptr<cc::KeyframedFilterAnimationCurve> m_curve;
 };
 
 } // namespace blink
diff --git a/third_party/WebKit/Source/platform/animation/CompositorFloatAnimationCurve.cpp b/third_party/WebKit/Source/platform/animation/CompositorFloatAnimationCurve.cpp
index 37fd92b..10574ac 100644
--- a/third_party/WebKit/Source/platform/animation/CompositorFloatAnimationCurve.cpp
+++ b/third_party/WebKit/Source/platform/animation/CompositorFloatAnimationCurve.cpp
@@ -78,7 +78,7 @@
     return m_curve->GetValue(base::TimeDelta::FromSecondsD(time));
 }
 
-scoped_ptr<cc::AnimationCurve> CompositorFloatAnimationCurve::cloneToAnimationCurve() const
+std::unique_ptr<cc::AnimationCurve> CompositorFloatAnimationCurve::cloneToAnimationCurve() const
 {
     return m_curve->Clone();
 }
diff --git a/third_party/WebKit/Source/platform/animation/CompositorFloatAnimationCurve.h b/third_party/WebKit/Source/platform/animation/CompositorFloatAnimationCurve.h
index 1fb0469..0362bfe7 100644
--- a/third_party/WebKit/Source/platform/animation/CompositorFloatAnimationCurve.h
+++ b/third_party/WebKit/Source/platform/animation/CompositorFloatAnimationCurve.h
@@ -5,12 +5,13 @@
 #ifndef CompositorFloatAnimationCurve_h
 #define CompositorFloatAnimationCurve_h
 
-#include "base/memory/scoped_ptr.h"
 #include "platform/PlatformExport.h"
 #include "platform/animation/CompositorAnimationCurve.h"
 #include "platform/animation/CompositorFloatKeyframe.h"
 #include "wtf/Noncopyable.h"
 
+#include <memory>
+
 namespace cc {
 class AnimationCurve;
 class KeyframedFloatAnimationCurve;
@@ -48,10 +49,10 @@
     // CompositorAnimationCurve implementation.
     AnimationCurveType type() const override;
 
-    scoped_ptr<cc::AnimationCurve> cloneToAnimationCurve() const;
+    std::unique_ptr<cc::AnimationCurve> cloneToAnimationCurve() const;
 
 private:
-    scoped_ptr<cc::KeyframedFloatAnimationCurve> m_curve;
+    std::unique_ptr<cc::KeyframedFloatAnimationCurve> m_curve;
 };
 
 } // namespace blink
diff --git a/third_party/WebKit/Source/platform/animation/CompositorFloatAnimationCurveTest.cpp b/third_party/WebKit/Source/platform/animation/CompositorFloatAnimationCurveTest.cpp
index 0f10b2d6..3046711 100644
--- a/third_party/WebKit/Source/platform/animation/CompositorFloatAnimationCurveTest.cpp
+++ b/third_party/WebKit/Source/platform/animation/CompositorFloatAnimationCurveTest.cpp
@@ -4,10 +4,11 @@
 
 #include "platform/animation/CompositorFloatAnimationCurve.h"
 
-#include "base/memory/scoped_ptr.h"
 #include "cc/animation/timing_function.h"
 #include "testing/gtest/include/gtest/gtest.h"
 
+#include <memory>
+
 using blink::CompositorAnimationCurve;
 using blink::CompositorFloatAnimationCurve;
 using blink::CompositorFloatKeyframe;
@@ -17,7 +18,7 @@
 // Tests that a float animation with one keyframe works as expected.
 TEST(WebFloatAnimationCurveTest, OneFloatKeyframe)
 {
-    scoped_ptr<CompositorFloatAnimationCurve> curve(new CompositorFloatAnimationCurve);
+    std::unique_ptr<CompositorFloatAnimationCurve> curve(new CompositorFloatAnimationCurve);
     curve->add(CompositorFloatKeyframe(0, 2),
         CompositorAnimationCurve::TimingFunctionTypeLinear);
     EXPECT_FLOAT_EQ(2, curve->getValue(-1));
@@ -30,7 +31,7 @@
 // Tests that a float animation with two keyframes works as expected.
 TEST(WebFloatAnimationCurveTest, TwoFloatKeyframe)
 {
-    scoped_ptr<CompositorFloatAnimationCurve> curve(new CompositorFloatAnimationCurve);
+    std::unique_ptr<CompositorFloatAnimationCurve> curve(new CompositorFloatAnimationCurve);
     curve->add(CompositorFloatKeyframe(0, 2),
         CompositorAnimationCurve::TimingFunctionTypeLinear);
     curve->add(CompositorFloatKeyframe(1, 4),
@@ -45,7 +46,7 @@
 // Tests that a float animation with three keyframes works as expected.
 TEST(WebFloatAnimationCurveTest, ThreeFloatKeyframe)
 {
-    scoped_ptr<CompositorFloatAnimationCurve> curve(new CompositorFloatAnimationCurve);
+    std::unique_ptr<CompositorFloatAnimationCurve> curve(new CompositorFloatAnimationCurve);
     curve->add(CompositorFloatKeyframe(0, 2),
         CompositorAnimationCurve::TimingFunctionTypeLinear);
     curve->add(CompositorFloatKeyframe(1, 4),
@@ -64,7 +65,7 @@
 // Tests that a float animation with multiple keys at a given time works sanely.
 TEST(WebFloatAnimationCurveTest, RepeatedFloatKeyTimes)
 {
-    scoped_ptr<CompositorFloatAnimationCurve> curve(new CompositorFloatAnimationCurve);
+    std::unique_ptr<CompositorFloatAnimationCurve> curve(new CompositorFloatAnimationCurve);
     curve->add(CompositorFloatKeyframe(0, 4),
         CompositorAnimationCurve::TimingFunctionTypeLinear);
     curve->add(CompositorFloatKeyframe(1, 4),
@@ -90,7 +91,7 @@
 // Tests that the keyframes may be added out of order.
 TEST(WebFloatAnimationCurveTest, UnsortedKeyframes)
 {
-    scoped_ptr<CompositorFloatAnimationCurve> curve(new CompositorFloatAnimationCurve);
+    std::unique_ptr<CompositorFloatAnimationCurve> curve(new CompositorFloatAnimationCurve);
     curve->add(CompositorFloatKeyframe(2, 8),
         CompositorAnimationCurve::TimingFunctionTypeLinear);
     curve->add(CompositorFloatKeyframe(0, 2),
@@ -110,7 +111,7 @@
 // Tests that a cubic bezier timing function works as expected.
 TEST(WebFloatAnimationCurveTest, CubicBezierTimingFunction)
 {
-    scoped_ptr<CompositorFloatAnimationCurve> curve(new CompositorFloatAnimationCurve);
+    std::unique_ptr<CompositorFloatAnimationCurve> curve(new CompositorFloatAnimationCurve);
     curve->add(CompositorFloatKeyframe(0, 0), 0.25, 0, 0.75, 1);
     curve->add(CompositorFloatKeyframe(1, 1),
         CompositorAnimationCurve::TimingFunctionTypeLinear);
@@ -127,13 +128,13 @@
 // Tests that an ease timing function works as expected.
 TEST(WebFloatAnimationCurveTest, EaseTimingFunction)
 {
-    scoped_ptr<CompositorFloatAnimationCurve> curve(new CompositorFloatAnimationCurve);
+    std::unique_ptr<CompositorFloatAnimationCurve> curve(new CompositorFloatAnimationCurve);
     curve->add(CompositorFloatKeyframe(0, 0),
         CompositorAnimationCurve::TimingFunctionTypeEase);
     curve->add(CompositorFloatKeyframe(1, 1),
         CompositorAnimationCurve::TimingFunctionTypeLinear);
 
-    scoped_ptr<cc::TimingFunction> timingFunction(
+    std::unique_ptr<cc::TimingFunction> timingFunction(
         cc::EaseTimingFunction::Create());
     for (int i = 0; i <= 4; ++i) {
         const double time = i * 0.25;
@@ -144,7 +145,7 @@
 // Tests using a linear timing function.
 TEST(WebFloatAnimationCurveTest, LinearTimingFunction)
 {
-    scoped_ptr<CompositorFloatAnimationCurve> curve(new CompositorFloatAnimationCurve);
+    std::unique_ptr<CompositorFloatAnimationCurve> curve(new CompositorFloatAnimationCurve);
     curve->add(CompositorFloatKeyframe(0, 0),
         CompositorAnimationCurve::TimingFunctionTypeLinear);
     curve->add(CompositorFloatKeyframe(1, 1),
@@ -159,13 +160,13 @@
 // Tests that an ease in timing function works as expected.
 TEST(WebFloatAnimationCurveTest, EaseInTimingFunction)
 {
-    scoped_ptr<CompositorFloatAnimationCurve> curve(new CompositorFloatAnimationCurve);
+    std::unique_ptr<CompositorFloatAnimationCurve> curve(new CompositorFloatAnimationCurve);
     curve->add(CompositorFloatKeyframe(0, 0),
         CompositorAnimationCurve::TimingFunctionTypeEaseIn);
     curve->add(CompositorFloatKeyframe(1, 1),
         CompositorAnimationCurve::TimingFunctionTypeLinear);
 
-    scoped_ptr<cc::TimingFunction> timingFunction(
+    std::unique_ptr<cc::TimingFunction> timingFunction(
         cc::EaseInTimingFunction::Create());
     for (int i = 0; i <= 4; ++i) {
         const double time = i * 0.25;
@@ -176,13 +177,13 @@
 // Tests that an ease in timing function works as expected.
 TEST(WebFloatAnimationCurveTest, EaseOutTimingFunction)
 {
-    scoped_ptr<CompositorFloatAnimationCurve> curve(new CompositorFloatAnimationCurve);
+    std::unique_ptr<CompositorFloatAnimationCurve> curve(new CompositorFloatAnimationCurve);
     curve->add(CompositorFloatKeyframe(0, 0),
         CompositorAnimationCurve::TimingFunctionTypeEaseOut);
     curve->add(CompositorFloatKeyframe(1, 1),
         CompositorAnimationCurve::TimingFunctionTypeLinear);
 
-    scoped_ptr<cc::TimingFunction> timingFunction(
+    std::unique_ptr<cc::TimingFunction> timingFunction(
         cc::EaseOutTimingFunction::Create());
     for (int i = 0; i <= 4; ++i) {
         const double time = i * 0.25;
@@ -193,13 +194,13 @@
 // Tests that an ease in timing function works as expected.
 TEST(WebFloatAnimationCurveTest, EaseInOutTimingFunction)
 {
-    scoped_ptr<CompositorFloatAnimationCurve> curve(new CompositorFloatAnimationCurve);
+    std::unique_ptr<CompositorFloatAnimationCurve> curve(new CompositorFloatAnimationCurve);
     curve->add(CompositorFloatKeyframe(0, 0),
         CompositorAnimationCurve::TimingFunctionTypeEaseInOut);
     curve->add(CompositorFloatKeyframe(1, 1),
         CompositorAnimationCurve::TimingFunctionTypeLinear);
 
-    scoped_ptr<cc::TimingFunction> timingFunction(
+    std::unique_ptr<cc::TimingFunction> timingFunction(
         cc::EaseInOutTimingFunction::Create());
     for (int i = 0; i <= 4; ++i) {
         const double time = i * 0.25;
@@ -210,7 +211,7 @@
 // Tests that an ease in timing function works as expected.
 TEST(WebFloatAnimationCurveTest, CustomBezierTimingFunction)
 {
-    scoped_ptr<CompositorFloatAnimationCurve> curve(new CompositorFloatAnimationCurve);
+    std::unique_ptr<CompositorFloatAnimationCurve> curve(new CompositorFloatAnimationCurve);
     double x1 = 0.3;
     double y1 = 0.2;
     double x2 = 0.8;
@@ -219,7 +220,7 @@
     curve->add(CompositorFloatKeyframe(1, 1),
         CompositorAnimationCurve::TimingFunctionTypeLinear);
 
-    scoped_ptr<cc::TimingFunction> timingFunction(
+    std::unique_ptr<cc::TimingFunction> timingFunction(
         cc::CubicBezierTimingFunction::Create(x1, y1, x2, y2));
     for (int i = 0; i <= 4; ++i) {
         const double time = i * 0.25;
@@ -230,12 +231,12 @@
 // Tests that the default timing function is indeed ease.
 TEST(WebFloatAnimationCurveTest, DefaultTimingFunction)
 {
-    scoped_ptr<CompositorFloatAnimationCurve> curve(new CompositorFloatAnimationCurve);
+    std::unique_ptr<CompositorFloatAnimationCurve> curve(new CompositorFloatAnimationCurve);
     curve->add(CompositorFloatKeyframe(0, 0));
     curve->add(CompositorFloatKeyframe(1, 1),
         CompositorAnimationCurve::TimingFunctionTypeLinear);
 
-    scoped_ptr<cc::TimingFunction> timingFunction(
+    std::unique_ptr<cc::TimingFunction> timingFunction(
         cc::EaseTimingFunction::Create());
     for (int i = 0; i <= 4; ++i) {
         const double time = i * 0.25;
diff --git a/third_party/WebKit/Source/platform/animation/CompositorScrollOffsetAnimationCurve.cpp b/third_party/WebKit/Source/platform/animation/CompositorScrollOffsetAnimationCurve.cpp
index f4202b3c..7aeb8f2 100644
--- a/third_party/WebKit/Source/platform/animation/CompositorScrollOffsetAnimationCurve.cpp
+++ b/third_party/WebKit/Source/platform/animation/CompositorScrollOffsetAnimationCurve.cpp
@@ -81,7 +81,7 @@
     m_curve->UpdateTarget(time, gfx::ScrollOffset(newTarget.x(), newTarget.y()));
 }
 
-scoped_ptr<cc::AnimationCurve> CompositorScrollOffsetAnimationCurve::cloneToAnimationCurve() const
+std::unique_ptr<cc::AnimationCurve> CompositorScrollOffsetAnimationCurve::cloneToAnimationCurve() const
 {
     return m_curve->Clone();
 }
diff --git a/third_party/WebKit/Source/platform/animation/CompositorScrollOffsetAnimationCurve.h b/third_party/WebKit/Source/platform/animation/CompositorScrollOffsetAnimationCurve.h
index 9a0e81b..2f13a48 100644
--- a/third_party/WebKit/Source/platform/animation/CompositorScrollOffsetAnimationCurve.h
+++ b/third_party/WebKit/Source/platform/animation/CompositorScrollOffsetAnimationCurve.h
@@ -5,12 +5,13 @@
 #ifndef CompositorScrollOffsetAnimationCurve_h
 #define CompositorScrollOffsetAnimationCurve_h
 
-#include "base/memory/scoped_ptr.h"
 #include "platform/PlatformExport.h"
 #include "platform/animation/CompositorAnimationCurve.h"
 #include "platform/geometry/FloatPoint.h"
 #include "wtf/Noncopyable.h"
 
+#include <memory>
+
 namespace cc {
 class AnimationCurve;
 class ScrollOffsetAnimationCurve;
@@ -40,10 +41,10 @@
     virtual FloatPoint targetValue() const;
     virtual void updateTarget(double time, FloatPoint newTarget);
 
-    scoped_ptr<cc::AnimationCurve> cloneToAnimationCurve() const;
+    std::unique_ptr<cc::AnimationCurve> cloneToAnimationCurve() const;
 
 private:
-    scoped_ptr<cc::ScrollOffsetAnimationCurve> m_curve;
+    std::unique_ptr<cc::ScrollOffsetAnimationCurve> m_curve;
 };
 
 } // namespace blink
diff --git a/third_party/WebKit/Source/platform/animation/CompositorTransformAnimationCurve.cpp b/third_party/WebKit/Source/platform/animation/CompositorTransformAnimationCurve.cpp
index 6bb27985..027f391 100644
--- a/third_party/WebKit/Source/platform/animation/CompositorTransformAnimationCurve.cpp
+++ b/third_party/WebKit/Source/platform/animation/CompositorTransformAnimationCurve.cpp
@@ -77,7 +77,7 @@
     m_curve->SetTimingFunction(cc::StepsTimingFunction::Create(numberOfSteps, stepsStartOffset));
 }
 
-scoped_ptr<cc::AnimationCurve> CompositorTransformAnimationCurve::cloneToAnimationCurve() const
+std::unique_ptr<cc::AnimationCurve> CompositorTransformAnimationCurve::cloneToAnimationCurve() const
 {
     return m_curve->Clone();
 }
diff --git a/third_party/WebKit/Source/platform/animation/CompositorTransformAnimationCurve.h b/third_party/WebKit/Source/platform/animation/CompositorTransformAnimationCurve.h
index 9cf9020..8b701725 100644
--- a/third_party/WebKit/Source/platform/animation/CompositorTransformAnimationCurve.h
+++ b/third_party/WebKit/Source/platform/animation/CompositorTransformAnimationCurve.h
@@ -5,12 +5,13 @@
 #ifndef CompositorTransformAnimationCurve_h
 #define CompositorTransformAnimationCurve_h
 
-#include "base/memory/scoped_ptr.h"
 #include "platform/PlatformExport.h"
 #include "platform/animation/CompositorAnimationCurve.h"
 #include "platform/animation/CompositorTransformKeyframe.h"
 #include "wtf/Noncopyable.h"
 
+#include <memory>
+
 namespace cc {
 class AnimationCurve;
 class KeyframedTransformAnimationCurve;
@@ -46,10 +47,10 @@
     // CompositorAnimationCurve implementation.
     AnimationCurveType type() const override;
 
-    scoped_ptr<cc::AnimationCurve> cloneToAnimationCurve() const;
+    std::unique_ptr<cc::AnimationCurve> cloneToAnimationCurve() const;
 
 private:
-    scoped_ptr<cc::KeyframedTransformAnimationCurve> m_curve;
+    std::unique_ptr<cc::KeyframedTransformAnimationCurve> m_curve;
 };
 
 } // namespace blink
diff --git a/third_party/WebKit/Source/platform/blink_platform.gypi b/third_party/WebKit/Source/platform/blink_platform.gypi
index 5b4ce41b..fa9b042 100644
--- a/third_party/WebKit/Source/platform/blink_platform.gypi
+++ b/third_party/WebKit/Source/platform/blink_platform.gypi
@@ -388,9 +388,6 @@
       'fonts/AcceptLanguagesResolver.h',
       'fonts/AlternateFontFamily.h',
       'fonts/CharacterRange.h',
-      'fonts/Character.cpp',
-      'fonts/Character.h',
-      'fonts/CharacterEmoji.cpp',
       'fonts/CustomFontData.h',
       'fonts/Font.cpp',
       'fonts/Font.h',
@@ -956,6 +953,9 @@
       'text/BidiRunList.h',
       'text/BidiTextRun.cpp',
       'text/BidiTextRun.h',
+      'text/Character.cpp',
+      'text/Character.h',
+      'text/CharacterEmoji.cpp',
       'text/CompressibleString.cpp',
       'text/CompressibleString.h',
       'text/DateTimeFormat.cpp',
@@ -1061,8 +1061,8 @@
       'v8_inspector/V8HeapProfilerAgentImpl.h',
       'v8_inspector/V8InjectedScriptHost.cpp',
       'v8_inspector/V8InjectedScriptHost.h',
-      'v8_inspector/V8InspectorConnectionImpl.cpp',
-      'v8_inspector/V8InspectorConnectionImpl.h',
+      'v8_inspector/V8InspectorSessionImpl.cpp',
+      'v8_inspector/V8InspectorSessionImpl.h',
       'v8_inspector/V8ProfilerAgentImpl.cpp',
       'v8_inspector/V8ProfilerAgentImpl.h',
       'v8_inspector/V8Regex.cpp',
@@ -1080,6 +1080,7 @@
       'v8_inspector/public/V8DebuggerAgent.h',
       'v8_inspector/public/V8DebuggerClient.h',
       'v8_inspector/public/V8HeapProfilerAgent.h',
+      'v8_inspector/public/V8InspectorSession.h',
       'v8_inspector/public/V8ProfilerAgent.h',
       'v8_inspector/public/V8RuntimeAgent.h',
       'v8_inspector/public/V8StackTrace.h',
@@ -1138,7 +1139,6 @@
       'clipboard/ClipboardUtilitiesTest.cpp',
       'exported/FilePathConversionTest.cpp',
       'fonts/AcceptLanguagesResolverTest.cpp',
-      'fonts/CharacterTest.cpp',
       'fonts/FontCacheTest.cpp',
       'fonts/FontDescriptionTest.cpp',
       'fonts/FontPlatformDataTest.cpp',
@@ -1202,6 +1202,7 @@
       'testing/TreeTestHelpers.cpp',
       'testing/TreeTestHelpers.h',
       'text/BidiResolverTest.cpp',
+      'text/CharacterTest.cpp',
       'text/DateTimeFormatTest.cpp',
       'text/LocaleToScriptMappingTest.cpp',
       'text/SegmentedStringTest.cpp',
diff --git a/third_party/WebKit/Source/platform/fonts/Font.cpp b/third_party/WebKit/Source/platform/fonts/Font.cpp
index a2ecac9e..64110d54 100644
--- a/third_party/WebKit/Source/platform/fonts/Font.cpp
+++ b/third_party/WebKit/Source/platform/fonts/Font.cpp
@@ -27,7 +27,6 @@
 #include "platform/LayoutTestSupport.h"
 #include "platform/LayoutUnit.h"
 #include "platform/RuntimeEnabledFeatures.h"
-#include "platform/fonts/Character.h"
 #include "platform/fonts/CharacterRange.h"
 #include "platform/fonts/FontCache.h"
 #include "platform/fonts/FontFallbackIterator.h"
@@ -41,6 +40,7 @@
 #include "platform/fonts/shaping/SimpleShaper.h"
 #include "platform/geometry/FloatRect.h"
 #include "platform/text/BidiResolver.h"
+#include "platform/text/Character.h"
 #include "platform/text/TextRun.h"
 #include "platform/text/TextRunIterator.h"
 #include "platform/transforms/AffineTransform.h"
diff --git a/third_party/WebKit/Source/platform/fonts/FontOrientation.h b/third_party/WebKit/Source/platform/fonts/FontOrientation.h
index 19d7e5f..84f59f5 100644
--- a/third_party/WebKit/Source/platform/fonts/FontOrientation.h
+++ b/third_party/WebKit/Source/platform/fonts/FontOrientation.h
@@ -26,7 +26,7 @@
 #ifndef FontOrientation_h
 #define FontOrientation_h
 
-#include "platform/fonts/Character.h"
+#include "platform/text/Character.h"
 
 namespace blink {
 
diff --git a/third_party/WebKit/Source/platform/fonts/FontPlatformData.cpp b/third_party/WebKit/Source/platform/fonts/FontPlatformData.cpp
index 05f279ad..110945c4 100644
--- a/third_party/WebKit/Source/platform/fonts/FontPlatformData.cpp
+++ b/third_party/WebKit/Source/platform/fonts/FontPlatformData.cpp
@@ -23,9 +23,9 @@
 #include "SkTypeface.h"
 #include "hb-ot.h"
 #include "hb.h"
-#include "platform/fonts/Character.h"
 #include "platform/fonts/FontCache.h"
 #include "platform/fonts/shaping/HarfBuzzFace.h"
+#include "platform/text/Character.h"
 #include "wtf/ByteSwap.h"
 #include "wtf/HashMap.h"
 #include "wtf/text/StringHash.h"
@@ -286,20 +286,20 @@
 bool FontPlatformData::hasSpaceInLigaturesOrKerning(
     TypesettingFeatures features) const
 {
-    const HarfBuzzFace* hbFace = harfBuzzFace();
+    HarfBuzzFace* hbFace = harfBuzzFace();
     if (!hbFace)
         return false;
 
     hb_face_t* face = hbFace->face();
     ASSERT(face);
-    OwnPtr<hb_font_t> font = adoptPtr(hbFace->createFont());
+    hb_font_t* font = hbFace->getScaledFont();
     ASSERT(font);
 
     hb_codepoint_t space;
     // If the space glyph isn't present in the font then each space character
     // will be rendering using a fallback font, which grantees that it cannot
     // affect the shape of the preceding word.
-    if (!hb_font_get_glyph(font.get(), spaceCharacter, 0, &space))
+    if (!hb_font_get_glyph(font, spaceCharacter, 0, &space))
         return false;
 
     if (!hb_ot_layout_has_substitution(face)
diff --git a/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzFace.cpp b/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzFace.cpp
index 402642e..cfec720 100644
--- a/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzFace.cpp
+++ b/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzFace.cpp
@@ -50,8 +50,6 @@
 
 namespace blink {
 
-const hb_tag_t HarfBuzzFace::vertTag = HB_TAG('v', 'e', 'r', 't');
-
 // Though we have FontCache class, which provides the cache mechanism for
 // WebKit's font objects, we also need additional caching layer for HarfBuzz
 // to reduce the memory consumption because hb_face_t should be associated with
@@ -70,7 +68,6 @@
     }
 
     hb_face_t* face() { return m_face; }
-    HashMap<uint32_t, uint16_t>* glyphCache() { return &m_glyphCache; }
 
 private:
     explicit FaceCacheEntry(hb_face_t* face)
@@ -78,7 +75,6 @@
     { }
 
     hb_face_t* m_face;
-    HashMap<uint32_t, uint16_t> m_glyphCache;
 };
 
 typedef HashMap<uint64_t, RefPtr<FaceCacheEntry>, WTF::IntHash<uint64_t>, WTF::UnsignedWithZeroKeyHashTraits<uint64_t>> HarfBuzzFaceCache;
@@ -98,7 +94,7 @@
         result.storedValue->value = FaceCacheEntry::create(createFace());
     result.storedValue->value->ref();
     m_face = result.storedValue->value->face();
-    m_glyphCacheForFaceCacheEntry = result.storedValue->value->glyphCache();
+    prepareHarfBuzzFontData();
 }
 
 HarfBuzzFace::~HarfBuzzFace()
@@ -111,27 +107,22 @@
         harfBuzzFaceCache()->remove(m_uniqueID);
 }
 
+// struct to carry user-pointer data for hb_font_t callback functions.
 struct HarfBuzzFontData {
     USING_FAST_MALLOC(HarfBuzzFontData);
     WTF_MAKE_NONCOPYABLE(HarfBuzzFontData);
 public:
+
+    HarfBuzzFontData() {}
     HarfBuzzFontData(WTF::HashMap<uint32_t, uint16_t>* glyphCacheForFaceCacheEntry, hb_face_t* face, PassRefPtr<UnicodeRangeSet> rangeSet)
-        : m_glyphCacheForFaceCacheEntry(glyphCacheForFaceCacheEntry)
-        , m_face(face)
+        : m_face(face)
         , m_hbOpenTypeFont(nullptr)
         , m_rangeSet(rangeSet)
     {
     }
 
-    ~HarfBuzzFontData()
-    {
-        if (m_hbOpenTypeFont)
-            hb_font_destroy(m_hbOpenTypeFont);
-    }
-
     SkPaint m_paint;
     RefPtr<SimpleFontData> m_simpleFontData;
-    WTF::HashMap<uint32_t, uint16_t>* m_glyphCacheForFaceCacheEntry;
     hb_face_t* m_face;
     hb_font_t* m_hbOpenTypeFont;
     RefPtr<UnicodeRangeSet> m_rangeSet;
@@ -175,10 +166,6 @@
     }
 }
 
-#if !defined(HB_VERSION_ATLEAST)
-#define HB_VERSION_ATLEAST(major, minor, micro) 0
-#endif
-
 static hb_bool_t harfBuzzGetGlyph(hb_font_t* hbFont, void* fontData, hb_codepoint_t unicode, hb_codepoint_t variationSelector, hb_codepoint_t* glyph, void* userData)
 {
     HarfBuzzFontData* hbFontData = reinterpret_cast<HarfBuzzFontData*>(fontData);
@@ -187,34 +174,7 @@
     if (hbFontData->m_rangeSet && !hbFontData->m_rangeSet->contains(unicode))
         return false;
 
-    if (variationSelector) {
-#if !HB_VERSION_ATLEAST(0, 9, 28)
-        return false;
-#else
-        // Skia does not support variation selectors, but hb does.
-        // We're not fully ready to switch to hb-ot-font yet,
-        // but are good enough to get glyph IDs for OpenType fonts.
-        if (!hbFontData->m_hbOpenTypeFont) {
-            hbFontData->m_hbOpenTypeFont = hb_font_create(hbFontData->m_face);
-            hb_ot_font_set_funcs(hbFontData->m_hbOpenTypeFont);
-        }
-        return hb_font_get_glyph(hbFontData->m_hbOpenTypeFont, unicode, variationSelector, glyph);
-        // When not found, glyph_func should return false rather than fallback to the base.
-        // http://lists.freedesktop.org/archives/harfbuzz/2015-May/004888.html
-#endif
-    }
-
-    WTF::HashMap<uint32_t, uint16_t>::AddResult result = hbFontData->m_glyphCacheForFaceCacheEntry->add(unicode, 0);
-    if (result.isNewEntry) {
-        SkPaint* paint = &hbFontData->m_paint;
-        paint->setTextEncoding(SkPaint::kUTF32_TextEncoding);
-        uint16_t glyph16;
-        paint->textToGlyphs(&unicode, sizeof(hb_codepoint_t), &glyph16);
-        result.storedValue->value = glyph16;
-        *glyph = glyph16;
-    }
-    *glyph = result.storedValue->value;
-    return !!*glyph;
+    return hb_font_get_glyph(hb_font_get_parent(hbFont), unicode, variationSelector, glyph);
 }
 
 static hb_position_t harfBuzzGetGlyphHorizontalAdvance(hb_font_t* hbFont, void* fontData, hb_codepoint_t glyph, void* userData)
@@ -226,13 +186,6 @@
     return advance;
 }
 
-static hb_bool_t harfBuzzGetGlyphHorizontalOrigin(hb_font_t* hbFont, void* fontData, hb_codepoint_t glyph, hb_position_t* x, hb_position_t* y, void* userData)
-{
-    // Just return true, following the way that HarfBuzz-FreeType
-    // implementation does.
-    return true;
-}
-
 static hb_bool_t harfBuzzGetGlyphVerticalOrigin(hb_font_t* hbFont, void* fontData, hb_codepoint_t glyph, hb_position_t* x, hb_position_t* y, void* userData)
 {
     HarfBuzzFontData* hbFontData = reinterpret_cast<HarfBuzzFontData*>(fontData);
@@ -301,7 +254,6 @@
         hb_font_funcs_set_glyph_func(harfBuzzSkiaFontFuncs, harfBuzzGetGlyph, 0, 0);
         hb_font_funcs_set_glyph_h_advance_func(harfBuzzSkiaFontFuncs, harfBuzzGetGlyphHorizontalAdvance, 0, 0);
         hb_font_funcs_set_glyph_h_kerning_func(harfBuzzSkiaFontFuncs, harfBuzzGetGlyphHorizontalKerning, 0, 0);
-        hb_font_funcs_set_glyph_h_origin_func(harfBuzzSkiaFontFuncs, harfBuzzGetGlyphHorizontalOrigin, 0, 0);
         hb_font_funcs_set_glyph_v_advance_func(harfBuzzSkiaFontFuncs, harfBuzzGetGlyphVerticalAdvance, 0, 0);
         hb_font_funcs_set_glyph_v_origin_func(harfBuzzSkiaFontFuncs, harfBuzzGetGlyphVerticalOrigin, 0, 0);
         hb_font_funcs_set_glyph_extents_func(harfBuzzSkiaFontFuncs, harfBuzzGetGlyphExtents, 0, 0);
@@ -333,12 +285,6 @@
 }
 #endif
 
-static void destroyHarfBuzzFontData(void* userData)
-{
-    HarfBuzzFontData* hbFontData = reinterpret_cast<HarfBuzzFontData*>(userData);
-    delete hbFontData;
-}
-
 hb_face_t* HarfBuzzFace::createFace()
 {
 #if OS(MACOSX)
@@ -350,19 +296,26 @@
     return face;
 }
 
-hb_font_t* HarfBuzzFace::createFont(PassRefPtr<UnicodeRangeSet> rangeSet) const
+void HarfBuzzFace::prepareHarfBuzzFontData()
 {
-    HarfBuzzFontData* hbFontData = new HarfBuzzFontData(m_glyphCacheForFaceCacheEntry, m_face, rangeSet);
-    m_platformData->setupPaint(&hbFontData->m_paint);
-    hbFontData->m_simpleFontData = FontCache::fontCache()->fontDataFromFontPlatformData(m_platformData);
-    ASSERT(hbFontData->m_simpleFontData);
-    hb_font_t* font = hb_font_create(m_face);
-    hb_font_set_funcs(font, harfBuzzSkiaGetFontFuncs(), hbFontData, destroyHarfBuzzFontData);
-    float size = m_platformData->size();
-    int scale = SkiaScalarToHarfBuzzPosition(size);
-    hb_font_set_scale(font, scale, scale);
-    hb_font_make_immutable(font);
-    return font;
+    m_harfBuzzFontData = adoptPtr(new HarfBuzzFontData());
+    m_harfBuzzFontData->m_simpleFontData = FontCache::fontCache()->fontDataFromFontPlatformData(m_platformData);
+    ASSERT(m_harfBuzzFontData->m_simpleFontData);
+    OwnPtr<hb_font_t> otFont = adoptPtr(hb_font_create(m_face));
+    hb_ot_font_set_funcs(otFont.get());
+    // Creating a sub font means that non-available functions
+    // are found from the parent.
+    m_unscaledFont = adoptPtr(hb_font_create_sub_font(otFont.get()));
+    hb_font_set_funcs(m_unscaledFont.get(), harfBuzzSkiaGetFontFuncs(), m_harfBuzzFontData.get(), nullptr);
+}
+
+hb_font_t* HarfBuzzFace::getScaledFont(PassRefPtr<UnicodeRangeSet> rangeSet)
+{
+    m_platformData->setupPaint(&m_harfBuzzFontData->m_paint);
+    m_harfBuzzFontData->m_rangeSet = rangeSet;
+    int scale = SkiaScalarToHarfBuzzPosition(m_platformData->size());
+    hb_font_set_scale(m_unscaledFont.get(), scale, scale);
+    return m_unscaledFont.get();
 }
 
 } // namespace blink
diff --git a/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzFace.h b/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzFace.h
index 9f7c15a..cdc3233 100644
--- a/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzFace.h
+++ b/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzFace.h
@@ -45,12 +45,11 @@
 namespace blink {
 
 class FontPlatformData;
+struct HarfBuzzFontData;
 
 class HarfBuzzFace : public RefCounted<HarfBuzzFace> {
     WTF_MAKE_NONCOPYABLE(HarfBuzzFace);
 public:
-    static const hb_tag_t vertTag;
-    static const hb_tag_t vrt2Tag;
 
     static PassRefPtr<HarfBuzzFace> create(FontPlatformData* platformData, uint64_t uniqueID)
     {
@@ -61,18 +60,20 @@
     // In order to support the restricting effect of unicode-range optionally a
     // range restriction can be passed in, which will restrict which glyphs we
     // return in the harfBuzzGetGlyph function.
-    hb_font_t* createFont(PassRefPtr<UnicodeRangeSet> = nullptr) const;
+    hb_font_t* getScaledFont(PassRefPtr<UnicodeRangeSet> = nullptr);
     hb_face_t* face() const { return m_face; }
 
 private:
     HarfBuzzFace(FontPlatformData*, uint64_t);
 
     hb_face_t* createFace();
+    void prepareHarfBuzzFontData();
 
     FontPlatformData* m_platformData;
     uint64_t m_uniqueID;
     hb_face_t* m_face;
-    WTF::HashMap<uint32_t, uint16_t>* m_glyphCacheForFaceCacheEntry;
+    OwnPtr<hb_font_t> m_unscaledFont;
+    OwnPtr<HarfBuzzFontData> m_harfBuzzFontData;
 };
 
 } // namespace blink
diff --git a/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzShaper.cpp b/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzShaper.cpp
index 932a5280..524657fa 100644
--- a/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzShaper.cpp
+++ b/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzShaper.cpp
@@ -32,7 +32,6 @@
 #include "platform/fonts/shaping/HarfBuzzShaper.h"
 
 #include "platform/Logging.h"
-#include "platform/fonts/Character.h"
 #include "platform/fonts/Font.h"
 #include "platform/fonts/FontFallbackIterator.h"
 #include "platform/fonts/GlyphBuffer.h"
@@ -40,6 +39,7 @@
 #include "platform/fonts/shaping/HarfBuzzFace.h"
 #include "platform/fonts/shaping/RunSegmenter.h"
 #include "platform/fonts/shaping/ShapeResultInlineHeaders.h"
+#include "platform/text/Character.h"
 #include "platform/text/TextBreakIterator.h"
 #include "wtf/Compiler.h"
 #include "wtf/MathExtras.h"
@@ -295,8 +295,8 @@
         m_font->getFontDescription(), m_normalizedBuffer.get(), m_normalizedBufferLength,
         startIndex, numCharacters);
 
-    HarfBuzzScopedPtr<hb_font_t> harfBuzzFont(face->createFont(currentFontRangeSet), hb_font_destroy);
-    hb_shape(harfBuzzFont.get(), harfBuzzBuffer, m_features.isEmpty() ? 0 : m_features.data(), m_features.size());
+    hb_font_t* hbFont = face->getScaledFont(currentFontRangeSet);
+    hb_shape(hbFont, harfBuzzBuffer, m_features.isEmpty() ? 0 : m_features.data(), m_features.size());
 
     return true;
 }
diff --git a/third_party/WebKit/Source/platform/fonts/shaping/RunSegmenter.cpp b/third_party/WebKit/Source/platform/fonts/shaping/RunSegmenter.cpp
index 8d774f6..859a2cb5 100644
--- a/third_party/WebKit/Source/platform/fonts/shaping/RunSegmenter.cpp
+++ b/third_party/WebKit/Source/platform/fonts/shaping/RunSegmenter.cpp
@@ -4,11 +4,11 @@
 
 #include "platform/fonts/shaping/RunSegmenter.h"
 
-#include "platform/fonts/Character.h"
 #include "platform/fonts/ScriptRunIterator.h"
 #include "platform/fonts/SmallCapsIterator.h"
 #include "platform/fonts/SymbolsIterator.h"
 #include "platform/fonts/UTF16TextIterator.h"
+#include "platform/text/Character.h"
 #include "wtf/Assertions.h"
 
 namespace blink {
diff --git a/third_party/WebKit/Source/platform/fonts/shaping/ShapeResultBuffer.cpp b/third_party/WebKit/Source/platform/fonts/shaping/ShapeResultBuffer.cpp
index e0a267b6..39a6ffc0 100644
--- a/third_party/WebKit/Source/platform/fonts/shaping/ShapeResultBuffer.cpp
+++ b/third_party/WebKit/Source/platform/fonts/shaping/ShapeResultBuffer.cpp
@@ -4,12 +4,12 @@
 
 #include "platform/fonts/shaping/ShapeResultBuffer.h"
 
-#include "platform/fonts/Character.h"
 #include "platform/fonts/CharacterRange.h"
 #include "platform/fonts/GlyphBuffer.h"
 #include "platform/fonts/SimpleFontData.h"
 #include "platform/fonts/shaping/ShapeResultInlineHeaders.h"
 #include "platform/geometry/FloatPoint.h"
+#include "platform/text/Character.h"
 #include "platform/text/TextBreakIterator.h"
 #include "platform/text/TextDirection.h"
 
diff --git a/third_party/WebKit/Source/platform/fonts/shaping/ShapeResultSpacing.h b/third_party/WebKit/Source/platform/fonts/shaping/ShapeResultSpacing.h
index 267b69a..926d8fb 100644
--- a/third_party/WebKit/Source/platform/fonts/shaping/ShapeResultSpacing.h
+++ b/third_party/WebKit/Source/platform/fonts/shaping/ShapeResultSpacing.h
@@ -6,7 +6,7 @@
 #define ShapeResultSpacing_h
 
 #include "platform/PlatformExport.h"
-#include "platform/fonts/Character.h"
+#include "platform/text/Character.h"
 
 namespace blink {
 
diff --git a/third_party/WebKit/Source/platform/fonts/shaping/SimpleShaper.cpp b/third_party/WebKit/Source/platform/fonts/shaping/SimpleShaper.cpp
index f1bc7a1c..07ea532 100644
--- a/third_party/WebKit/Source/platform/fonts/shaping/SimpleShaper.cpp
+++ b/third_party/WebKit/Source/platform/fonts/shaping/SimpleShaper.cpp
@@ -22,12 +22,12 @@
 
 #include "platform/fonts/shaping/SimpleShaper.h"
 
-#include "platform/fonts/Character.h"
 #include "platform/fonts/Font.h"
 #include "platform/fonts/GlyphBuffer.h"
 #include "platform/fonts/Latin1TextIterator.h"
 #include "platform/fonts/SimpleFontData.h"
 #include "platform/fonts/UTF16TextIterator.h"
+#include "platform/text/Character.h"
 #include "wtf/MathExtras.h"
 #include "wtf/text/CharacterNames.h"
 
diff --git a/third_party/WebKit/Source/platform/graphics/Canvas2DLayerBridgeTest.cpp b/third_party/WebKit/Source/platform/graphics/Canvas2DLayerBridgeTest.cpp
index 01f6178..9559718 100644
--- a/third_party/WebKit/Source/platform/graphics/Canvas2DLayerBridgeTest.cpp
+++ b/third_party/WebKit/Source/platform/graphics/Canvas2DLayerBridgeTest.cpp
@@ -25,7 +25,6 @@
 #include "platform/graphics/Canvas2DLayerBridge.h"
 
 #include "SkSurface.h"
-#include "base/memory/scoped_ptr.h"
 #include "gpu/command_buffer/client/gles2_interface.h"
 #include "platform/Task.h"
 #include "platform/ThreadSafeFunctional.h"
@@ -51,6 +50,8 @@
 #include "third_party/skia/include/gpu/gl/GrGLTypes.h"
 #include "wtf/RefPtr.h"
 
+#include <memory>
+
 using testing::AnyNumber;
 using testing::AtLeast;
 using testing::InSequence;
diff --git a/third_party/WebKit/Source/platform/graphics/CompositorMutableStateTest.cpp b/third_party/WebKit/Source/platform/graphics/CompositorMutableStateTest.cpp
index ec33486..a6b4423 100644
--- a/third_party/WebKit/Source/platform/graphics/CompositorMutableStateTest.cpp
+++ b/third_party/WebKit/Source/platform/graphics/CompositorMutableStateTest.cpp
@@ -65,15 +65,15 @@
     TestSharedBitmapManager m_sharedBitmapManager;
     TestTaskGraphRunner m_taskGraphRunner;
     FakeImplTaskRunnerProvider m_taskRunnerProvider;
-    scoped_ptr<OutputSurface> m_outputSurface;
-    scoped_ptr<FakeLayerTreeHostImpl> m_hostImpl;
+    std::unique_ptr<OutputSurface> m_outputSurface;
+    std::unique_ptr<FakeLayerTreeHostImpl> m_hostImpl;
 };
 
 TEST_F(CompositorMutableStateTest, NoMutableState)
 {
     // In this test, there are no layers with either an element id or mutable
     // properties. We should not be able to get any mutable state.
-    scoped_ptr<LayerImpl> root = LayerImpl::Create(hostImpl().active_tree(), 42);
+    std::unique_ptr<LayerImpl> root = LayerImpl::Create(hostImpl().active_tree(), 42);
     SetLayerPropertiesForTesting(root.get());
 
     hostImpl().SetViewportSize(root->bounds());
@@ -90,7 +90,7 @@
 {
     // In this test, there is a layer with an element id, but no mutable
     // properties. This should behave just as if we'd had no element id.
-    scoped_ptr<LayerImpl> root = LayerImpl::Create(hostImpl().active_tree(), 42);
+    std::unique_ptr<LayerImpl> root = LayerImpl::Create(hostImpl().active_tree(), 42);
     SetLayerPropertiesForTesting(root.get());
     root->SetElementId(42);
 
@@ -109,9 +109,9 @@
     // In this test, there is a layer with an element id and mutable properties.
     // In this case, we should get a valid mutable state for this element id that
     // has a real effect on the corresponding layer.
-    scoped_ptr<LayerImpl> root = LayerImpl::Create(hostImpl().active_tree(), 42);
+    std::unique_ptr<LayerImpl> root = LayerImpl::Create(hostImpl().active_tree(), 42);
 
-    scoped_ptr<LayerImpl> scopedLayer =
+    std::unique_ptr<LayerImpl> scopedLayer =
         LayerImpl::Create(hostImpl().active_tree(), 11);
     LayerImpl* layer = scopedLayer.get();
     layer->SetScrollClipLayer(root->id());
diff --git a/third_party/WebKit/Source/platform/graphics/GraphicsLayer.cpp b/third_party/WebKit/Source/platform/graphics/GraphicsLayer.cpp
index fa423c6..e7cdddf 100644
--- a/third_party/WebKit/Source/platform/graphics/GraphicsLayer.cpp
+++ b/third_party/WebKit/Source/platform/graphics/GraphicsLayer.cpp
@@ -1196,9 +1196,9 @@
     }
 }
 
-scoped_ptr<base::trace_event::ConvertableToTraceFormat> GraphicsLayer::TakeDebugInfo(cc::Layer* layer)
+std::unique_ptr<base::trace_event::ConvertableToTraceFormat> GraphicsLayer::TakeDebugInfo(cc::Layer* layer)
 {
-    scoped_ptr<base::trace_event::TracedValue> tracedValue(m_debugInfo.asTracedValue());
+    std::unique_ptr<base::trace_event::TracedValue> tracedValue(m_debugInfo.asTracedValue());
     tracedValue->SetString("layer_name", WTF::StringUTF8Adaptor(debugName(layer)).asStringPiece());
     return std::move(tracedValue);
 }
diff --git a/third_party/WebKit/Source/platform/graphics/GraphicsLayer.h b/third_party/WebKit/Source/platform/graphics/GraphicsLayer.h
index ca6581cd..2977f23 100644
--- a/third_party/WebKit/Source/platform/graphics/GraphicsLayer.h
+++ b/third_party/WebKit/Source/platform/graphics/GraphicsLayer.h
@@ -234,7 +234,7 @@
     void didScroll() override;
 
     // cc::LayerClient implementation.
-    scoped_ptr<base::trace_event::ConvertableToTraceFormat> TakeDebugInfo(cc::Layer*) override;
+    std::unique_ptr<base::trace_event::ConvertableToTraceFormat> TakeDebugInfo(cc::Layer*) override;
 
     PaintController& getPaintController();
 
diff --git a/third_party/WebKit/Source/platform/graphics/GraphicsLayerDebugInfo.cpp b/third_party/WebKit/Source/platform/graphics/GraphicsLayerDebugInfo.cpp
index 12f68b8..2abc2db4 100644
--- a/third_party/WebKit/Source/platform/graphics/GraphicsLayerDebugInfo.cpp
+++ b/third_party/WebKit/Source/platform/graphics/GraphicsLayerDebugInfo.cpp
@@ -32,9 +32,9 @@
 
 GraphicsLayerDebugInfo::~GraphicsLayerDebugInfo() { }
 
-scoped_ptr<base::trace_event::TracedValue> GraphicsLayerDebugInfo::asTracedValue() const
+std::unique_ptr<base::trace_event::TracedValue> GraphicsLayerDebugInfo::asTracedValue() const
 {
-    scoped_ptr<base::trace_event::TracedValue> tracedValue(
+    std::unique_ptr<base::trace_event::TracedValue> tracedValue(
         new base::trace_event::TracedValue());
     appendAnnotatedInvalidateRects(tracedValue.get());
     appendCompositingReasons(tracedValue.get());
diff --git a/third_party/WebKit/Source/platform/graphics/GraphicsLayerDebugInfo.h b/third_party/WebKit/Source/platform/graphics/GraphicsLayerDebugInfo.h
index 50beb17..183f7e3 100644
--- a/third_party/WebKit/Source/platform/graphics/GraphicsLayerDebugInfo.h
+++ b/third_party/WebKit/Source/platform/graphics/GraphicsLayerDebugInfo.h
@@ -31,7 +31,6 @@
 #ifndef GraphicsLayerDebugInfo_h
 #define GraphicsLayerDebugInfo_h
 
-#include "base/memory/scoped_ptr.h"
 #include "platform/geometry/FloatRect.h"
 #include "platform/graphics/CompositingReasons.h"
 #include "platform/graphics/PaintInvalidationReason.h"
@@ -40,6 +39,8 @@
 #include "wtf/Noncopyable.h"
 #include "wtf/Vector.h"
 
+#include <memory>
+
 namespace base {
 namespace trace_event {
 class TracedValue;
@@ -55,7 +56,7 @@
     GraphicsLayerDebugInfo();
     ~GraphicsLayerDebugInfo();
 
-    scoped_ptr<base::trace_event::TracedValue> asTracedValue() const;
+    std::unique_ptr<base::trace_event::TracedValue> asTracedValue() const;
 
     CompositingReasons getCompositingReasons() const { return m_compositingReasons; }
     void setCompositingReasons(CompositingReasons reasons) { m_compositingReasons = reasons; }
diff --git a/third_party/WebKit/Source/platform/platform_generated.gyp b/third_party/WebKit/Source/platform/platform_generated.gyp
index 0d6530b..82d5bc3 100644
--- a/third_party/WebKit/Source/platform/platform_generated.gyp
+++ b/third_party/WebKit/Source/platform/platform_generated.gyp
@@ -141,8 +141,8 @@
         {
           'action_name': 'CharacterPropertyData',
           'inputs': [
-            'fonts/CharacterPropertyDataGenerator.cpp',
-            'fonts/CharacterPropertyDataGenerator.h'
+            'text/CharacterPropertyDataGenerator.cpp',
+            'text/CharacterPropertyDataGenerator.h'
           ],
           'outputs': [
             '<(blink_platform_output_dir)/CharacterPropertyData.cpp',
@@ -156,7 +156,7 @@
             }, {
               'action': [
                 'cp',
-                'fonts/CharacterPropertyData.cpp',
+                'text/CharacterPropertyData.cpp',
                 '<(blink_platform_output_dir)/CharacterPropertyData.cpp',
               ],
             }]
@@ -169,7 +169,7 @@
       'type': 'executable',
       'toolsets': ['host'],
       'sources': [
-        'fonts/CharacterPropertyDataGenerator.cpp',
+        'text/CharacterPropertyDataGenerator.cpp',
       ],
       'dependencies': [
         '<(DEPTH)/third_party/icu/icu.gyp:icuuc#host',
diff --git a/third_party/WebKit/Source/platform/scroll/ScrollAnimator.cpp b/third_party/WebKit/Source/platform/scroll/ScrollAnimator.cpp
index 3f5cd774..de40738 100644
--- a/third_party/WebKit/Source/platform/scroll/ScrollAnimator.cpp
+++ b/third_party/WebKit/Source/platform/scroll/ScrollAnimator.cpp
@@ -371,7 +371,7 @@
 void ScrollAnimator::notifyAnimationTakeover(
     double monotonicTime,
     double animationStartTime,
-    scoped_ptr<cc::AnimationCurve> curve)
+    std::unique_ptr<cc::AnimationCurve> curve)
 {
     // If there is already an animation running and the compositor asks to take
     // over an animation, do nothing to avoid judder.
diff --git a/third_party/WebKit/Source/platform/scroll/ScrollAnimator.h b/third_party/WebKit/Source/platform/scroll/ScrollAnimator.h
index ea8676b..be1a269 100644
--- a/third_party/WebKit/Source/platform/scroll/ScrollAnimator.h
+++ b/third_party/WebKit/Source/platform/scroll/ScrollAnimator.h
@@ -74,7 +74,7 @@
     void notifyAnimationTakeover(
         double monotonicTime,
         double animationStartTime,
-        scoped_ptr<cc::AnimationCurve>) override;
+        std::unique_ptr<cc::AnimationCurve>) override;
 
     OwnPtr<CompositorScrollOffsetAnimationCurve> m_animationCurve;
     double m_startTime;
diff --git a/third_party/WebKit/Source/platform/scroll/ScrollAnimatorCompositorCoordinator.h b/third_party/WebKit/Source/platform/scroll/ScrollAnimatorCompositorCoordinator.h
index c4e493f..6819510 100644
--- a/third_party/WebKit/Source/platform/scroll/ScrollAnimatorCompositorCoordinator.h
+++ b/third_party/WebKit/Source/platform/scroll/ScrollAnimatorCompositorCoordinator.h
@@ -72,7 +72,7 @@
     void notifyAnimationTakeover(
         double monotonicTime,
         double animationStartTime,
-        scoped_ptr<cc::AnimationCurve>) override { };
+        std::unique_ptr<cc::AnimationCurve>) override { };
 
     // CompositorAnimationPlayerClient implementation.
     CompositorAnimationPlayer* compositorPlayer() const override;
diff --git a/third_party/WebKit/Source/platform/testing/WebLayerTreeViewImplForTesting.h b/third_party/WebKit/Source/platform/testing/WebLayerTreeViewImplForTesting.h
index b3ed0a3c..eb3657d8 100644
--- a/third_party/WebKit/Source/platform/testing/WebLayerTreeViewImplForTesting.h
+++ b/third_party/WebKit/Source/platform/testing/WebLayerTreeViewImplForTesting.h
@@ -5,13 +5,14 @@
 #ifndef WebLayerTreeViewImplForTesting_h
 #define WebLayerTreeViewImplForTesting_h
 
-#include "base/memory/scoped_ptr.h"
 #include "cc/test/test_task_graph_runner.h"
 #include "cc/trees/layer_tree_host_client.h"
 #include "cc/trees/layer_tree_host_single_thread_client.h"
 #include "public/platform/WebLayerTreeView.h"
 #include "wtf/PassOwnPtr.h"
 
+#include <memory>
+
 namespace cc {
 class LayerTreeHost;
 }
@@ -88,8 +89,8 @@
     void DidCompleteSwapBuffers() override {}
     void DidCompletePageScaleAnimation() override {}
     void RecordFrameTimingEvents(
-        scoped_ptr<cc::FrameTimingTracker::CompositeTimingSet> compositeEvents,
-        scoped_ptr<cc::FrameTimingTracker::MainFrameTimingSet> mainFrameEvents)
+        std::unique_ptr<cc::FrameTimingTracker::CompositeTimingSet> compositeEvents,
+        std::unique_ptr<cc::FrameTimingTracker::MainFrameTimingSet> mainFrameEvents)
         override {}
 
     // cc::LayerTreeHostSingleThreadClient implementation.
@@ -98,7 +99,7 @@
 
 private:
     cc::TestTaskGraphRunner m_taskGraphRunner;
-    scoped_ptr<cc::LayerTreeHost> m_layerTreeHost;
+    std::unique_ptr<cc::LayerTreeHost> m_layerTreeHost;
 };
 
 } // namespace blink
diff --git a/third_party/WebKit/Source/platform/fonts/Character.cpp b/third_party/WebKit/Source/platform/text/Character.cpp
similarity index 99%
rename from third_party/WebKit/Source/platform/fonts/Character.cpp
rename to third_party/WebKit/Source/platform/text/Character.cpp
index e95bc13..d59ae41b 100644
--- a/third_party/WebKit/Source/platform/fonts/Character.cpp
+++ b/third_party/WebKit/Source/platform/text/Character.cpp
@@ -28,7 +28,7 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#include "platform/fonts/Character.h"
+#include "platform/text/Character.h"
 
 #include "wtf/StdLibExtras.h"
 #include "wtf/text/StringBuilder.h"
diff --git a/third_party/WebKit/Source/platform/fonts/Character.h b/third_party/WebKit/Source/platform/text/Character.h
similarity index 99%
rename from third_party/WebKit/Source/platform/fonts/Character.h
rename to third_party/WebKit/Source/platform/text/Character.h
index 12dbb655..2f64ac5 100644
--- a/third_party/WebKit/Source/platform/fonts/Character.h
+++ b/third_party/WebKit/Source/platform/text/Character.h
@@ -32,7 +32,7 @@
 #define Character_h
 
 #include "platform/PlatformExport.h"
-#include "platform/fonts/CharacterProperty.h"
+#include "platform/text/CharacterProperty.h"
 #include "platform/text/TextDirection.h"
 #include "platform/text/TextPath.h"
 #include "platform/text/TextRun.h"
diff --git a/third_party/WebKit/Source/platform/fonts/CharacterEmoji.cpp b/third_party/WebKit/Source/platform/text/CharacterEmoji.cpp
similarity index 99%
rename from third_party/WebKit/Source/platform/fonts/CharacterEmoji.cpp
rename to third_party/WebKit/Source/platform/text/CharacterEmoji.cpp
index bf23801..e0fbb83 100644
--- a/third_party/WebKit/Source/platform/fonts/CharacterEmoji.cpp
+++ b/third_party/WebKit/Source/platform/text/CharacterEmoji.cpp
@@ -2,7 +2,7 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#include "platform/fonts/Character.h"
+#include "platform/text/Character.h"
 
 #include <unicode/uniset.h>
 
diff --git a/third_party/WebKit/Source/platform/fonts/CharacterProperty.h b/third_party/WebKit/Source/platform/text/CharacterProperty.h
similarity index 100%
rename from third_party/WebKit/Source/platform/fonts/CharacterProperty.h
rename to third_party/WebKit/Source/platform/text/CharacterProperty.h
diff --git a/third_party/WebKit/Source/platform/fonts/CharacterPropertyData.cpp b/third_party/WebKit/Source/platform/text/CharacterPropertyData.cpp
similarity index 100%
rename from third_party/WebKit/Source/platform/fonts/CharacterPropertyData.cpp
rename to third_party/WebKit/Source/platform/text/CharacterPropertyData.cpp
diff --git a/third_party/WebKit/Source/platform/fonts/CharacterPropertyDataGenerator.cpp b/third_party/WebKit/Source/platform/text/CharacterPropertyDataGenerator.cpp
similarity index 100%
rename from third_party/WebKit/Source/platform/fonts/CharacterPropertyDataGenerator.cpp
rename to third_party/WebKit/Source/platform/text/CharacterPropertyDataGenerator.cpp
diff --git a/third_party/WebKit/Source/platform/fonts/CharacterPropertyDataGenerator.h b/third_party/WebKit/Source/platform/text/CharacterPropertyDataGenerator.h
similarity index 100%
rename from third_party/WebKit/Source/platform/fonts/CharacterPropertyDataGenerator.h
rename to third_party/WebKit/Source/platform/text/CharacterPropertyDataGenerator.h
diff --git a/third_party/WebKit/Source/platform/fonts/CharacterTest.cpp b/third_party/WebKit/Source/platform/text/CharacterTest.cpp
similarity index 99%
rename from third_party/WebKit/Source/platform/fonts/CharacterTest.cpp
rename to third_party/WebKit/Source/platform/text/CharacterTest.cpp
index b6de727..c47d67a4 100644
--- a/third_party/WebKit/Source/platform/fonts/CharacterTest.cpp
+++ b/third_party/WebKit/Source/platform/text/CharacterTest.cpp
@@ -2,7 +2,7 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#include "platform/fonts/Character.h"
+#include "platform/text/Character.h"
 
 #include "platform/Logging.h"
 #include "testing/gtest/include/gtest/gtest.h"
diff --git a/third_party/WebKit/Source/platform/text/TextBreakIterator.cpp b/third_party/WebKit/Source/platform/text/TextBreakIterator.cpp
index 8c84c54..2f3387f 100644
--- a/third_party/WebKit/Source/platform/text/TextBreakIterator.cpp
+++ b/third_party/WebKit/Source/platform/text/TextBreakIterator.cpp
@@ -22,7 +22,7 @@
 
 #include "platform/text/TextBreakIterator.h"
 
-#include "platform/fonts/Character.h"
+#include "platform/text/Character.h"
 #include "wtf/ASCIICType.h"
 #include "wtf/StdLibExtras.h"
 #include "wtf/text/CharacterNames.h"
diff --git a/third_party/WebKit/Source/platform/text/TextRun.cpp b/third_party/WebKit/Source/platform/text/TextRun.cpp
index 18c1d61..25e2bd9 100644
--- a/third_party/WebKit/Source/platform/text/TextRun.cpp
+++ b/third_party/WebKit/Source/platform/text/TextRun.cpp
@@ -25,7 +25,7 @@
 
 #include "platform/text/TextRun.h"
 
-#include "platform/fonts/Character.h"
+#include "platform/text/Character.h"
 
 namespace blink {
 
diff --git a/third_party/WebKit/Source/platform/v8_inspector/InjectedScriptHost.cpp b/third_party/WebKit/Source/platform/v8_inspector/InjectedScriptHost.cpp
index 7b0b1cca..193b646 100644
--- a/third_party/WebKit/Source/platform/v8_inspector/InjectedScriptHost.cpp
+++ b/third_party/WebKit/Source/platform/v8_inspector/InjectedScriptHost.cpp
@@ -33,19 +33,19 @@
 #include "platform/inspector_protocol/String16.h"
 #include "platform/inspector_protocol/Values.h"
 #include "platform/v8_inspector/V8DebuggerAgentImpl.h"
-#include "platform/v8_inspector/V8InspectorConnectionImpl.h"
+#include "platform/v8_inspector/V8InspectorSessionImpl.h"
 #include "platform/v8_inspector/public/V8Debugger.h"
 
 namespace blink {
 
-PassOwnPtr<InjectedScriptHost> InjectedScriptHost::create(V8DebuggerImpl* debugger, V8InspectorConnectionImpl* connection)
+PassOwnPtr<InjectedScriptHost> InjectedScriptHost::create(V8DebuggerImpl* debugger, V8InspectorSessionImpl* session)
 {
-    return adoptPtr(new InjectedScriptHost(debugger, connection));
+    return adoptPtr(new InjectedScriptHost(debugger, session));
 }
 
-InjectedScriptHost::InjectedScriptHost(V8DebuggerImpl* debugger, V8InspectorConnectionImpl* connection)
+InjectedScriptHost::InjectedScriptHost(V8DebuggerImpl* debugger, V8InspectorSessionImpl* session)
     : m_debugger(debugger)
-    , m_connection(connection)
+    , m_session(session)
 {
 }
 
@@ -56,23 +56,23 @@
 void InjectedScriptHost::disconnect()
 {
     m_debugger = nullptr;
-    m_connection = nullptr;
+    m_session = nullptr;
     m_inspectedObjects.clear();
 }
 
 void InjectedScriptHost::inspectImpl(PassOwnPtr<protocol::Value> object, PassOwnPtr<protocol::Value> hints)
 {
-    if (m_connection && m_connection->inspectCallback()) {
+    if (m_session && m_session->inspectCallback()) {
         protocol::ErrorSupport errors;
         OwnPtr<protocol::Runtime::RemoteObject> remoteObject = protocol::Runtime::RemoteObject::parse(object.get(), &errors);
-        (*m_connection->inspectCallback())(remoteObject.release(), protocol::DictionaryValue::cast(hints));
+        (*m_session->inspectCallback())(remoteObject.release(), protocol::DictionaryValue::cast(hints));
     }
 }
 
 void InjectedScriptHost::clearConsoleMessages()
 {
-    if (m_connection && m_connection->clearConsoleCallback())
-        (*m_connection->clearConsoleCallback())();
+    if (m_session && m_session->clearConsoleCallback())
+        (*m_session->clearConsoleCallback())();
 }
 
 void InjectedScriptHost::addInspectedObject(PassOwnPtr<V8RuntimeAgent::Inspectable> object)
@@ -96,14 +96,14 @@
 
 void InjectedScriptHost::debugFunction(const String16& scriptId, int lineNumber, int columnNumber)
 {
-    if (m_connection && m_connection->debuggerAgent())
-        m_connection->debuggerAgent()->setBreakpointAt(scriptId, lineNumber, columnNumber, V8DebuggerAgentImpl::DebugCommandBreakpointSource);
+    if (m_session)
+        m_session->debuggerAgentImpl()->setBreakpointAt(scriptId, lineNumber, columnNumber, V8DebuggerAgentImpl::DebugCommandBreakpointSource);
 }
 
 void InjectedScriptHost::undebugFunction(const String16& scriptId, int lineNumber, int columnNumber)
 {
-    if (m_connection && m_connection->debuggerAgent())
-        m_connection->debuggerAgent()->removeBreakpointAt(scriptId, lineNumber, columnNumber, V8DebuggerAgentImpl::DebugCommandBreakpointSource);
+    if (m_session)
+        m_session->debuggerAgentImpl()->removeBreakpointAt(scriptId, lineNumber, columnNumber, V8DebuggerAgentImpl::DebugCommandBreakpointSource);
 }
 
 void InjectedScriptHost::monitorFunction(const String16& scriptId, int lineNumber, int columnNumber, const String16& functionName)
@@ -115,14 +115,14 @@
     else
         builder.append(functionName);
     builder.append(" called\" + (arguments.length > 0 ? \" with arguments: \" + Array.prototype.join.call(arguments, \", \") : \"\")) && false");
-    if (m_connection && m_connection->debuggerAgent())
-        m_connection->debuggerAgent()->setBreakpointAt(scriptId, lineNumber, columnNumber, V8DebuggerAgentImpl::MonitorCommandBreakpointSource, builder.toString());
+    if (m_session)
+        m_session->debuggerAgentImpl()->setBreakpointAt(scriptId, lineNumber, columnNumber, V8DebuggerAgentImpl::MonitorCommandBreakpointSource, builder.toString());
 }
 
 void InjectedScriptHost::unmonitorFunction(const String16& scriptId, int lineNumber, int columnNumber)
 {
-    if (m_connection && m_connection->debuggerAgent())
-        m_connection->debuggerAgent()->removeBreakpointAt(scriptId, lineNumber, columnNumber, V8DebuggerAgentImpl::MonitorCommandBreakpointSource);
+    if (m_session)
+        m_session->debuggerAgentImpl()->removeBreakpointAt(scriptId, lineNumber, columnNumber, V8DebuggerAgentImpl::MonitorCommandBreakpointSource);
 }
 
 } // namespace blink
diff --git a/third_party/WebKit/Source/platform/v8_inspector/InjectedScriptHost.h b/third_party/WebKit/Source/platform/v8_inspector/InjectedScriptHost.h
index 98657e8..46300f5 100644
--- a/third_party/WebKit/Source/platform/v8_inspector/InjectedScriptHost.h
+++ b/third_party/WebKit/Source/platform/v8_inspector/InjectedScriptHost.h
@@ -38,7 +38,7 @@
 
 namespace blink {
 
-class V8InspectorConnectionImpl;
+class V8InspectorSessionImpl;
 class V8EventListenerInfo;
 class V8DebuggerImpl;
 
@@ -53,7 +53,7 @@
 
 class InjectedScriptHost {
 public:
-    static PassOwnPtr<InjectedScriptHost> create(V8DebuggerImpl*, V8InspectorConnectionImpl*);
+    static PassOwnPtr<InjectedScriptHost> create(V8DebuggerImpl*, V8InspectorSessionImpl*);
     ~InjectedScriptHost();
 
     void disconnect();
@@ -77,10 +77,10 @@
     v8::Local<v8::FunctionTemplate> wrapperTemplate(v8::Isolate* isolate) { return v8::Local<v8::FunctionTemplate>::New(isolate, m_wrapperTemplate); }
 
 private:
-    InjectedScriptHost(V8DebuggerImpl*, V8InspectorConnectionImpl*);
+    InjectedScriptHost(V8DebuggerImpl*, V8InspectorSessionImpl*);
 
     V8DebuggerImpl* m_debugger;
-    V8InspectorConnectionImpl* m_connection;
+    V8InspectorSessionImpl* m_session;
     OwnPtr<V8RuntimeAgent::InspectCallback> m_inspectCallback;
     OwnPtr<V8RuntimeAgent::ClearConsoleCallback> m_clearConsoleCallback;
     protocol::Vector<OwnPtr<V8RuntimeAgent::Inspectable>> m_inspectedObjects;
diff --git a/third_party/WebKit/Source/platform/v8_inspector/V8DebuggerAgentImpl.cpp b/third_party/WebKit/Source/platform/v8_inspector/V8DebuggerAgentImpl.cpp
index 04cf981..74475932 100644
--- a/third_party/WebKit/Source/platform/v8_inspector/V8DebuggerAgentImpl.cpp
+++ b/third_party/WebKit/Source/platform/v8_inspector/V8DebuggerAgentImpl.cpp
@@ -13,7 +13,7 @@
 #include "platform/v8_inspector/MuteConsoleScope.h"
 #include "platform/v8_inspector/RemoteObjectId.h"
 #include "platform/v8_inspector/ScriptBreakpoint.h"
-#include "platform/v8_inspector/V8InspectorConnectionImpl.h"
+#include "platform/v8_inspector/V8InspectorSessionImpl.h"
 #include "platform/v8_inspector/V8Regex.h"
 #include "platform/v8_inspector/V8RuntimeAgentImpl.h"
 #include "platform/v8_inspector/V8StackTraceImpl.h"
@@ -157,19 +157,13 @@
         .setColumnNumber(columnNumber).build();
 }
 
-PassOwnPtr<V8DebuggerAgent> V8DebuggerAgent::create(V8RuntimeAgent* runtimeAgent)
-{
-    V8RuntimeAgentImpl* runtimeAgentImpl = static_cast<V8RuntimeAgentImpl*>(runtimeAgent);
-    return adoptPtr(new V8DebuggerAgentImpl(runtimeAgentImpl->connection(), runtimeAgentImpl->debugger()));
-}
-
-V8DebuggerAgentImpl::V8DebuggerAgentImpl(V8InspectorConnectionImpl* connection, V8DebuggerImpl* debugger)
-    : m_debugger(debugger)
-    , m_connection(connection)
+V8DebuggerAgentImpl::V8DebuggerAgentImpl(V8InspectorSessionImpl* session)
+    : m_debugger(session->debugger())
+    , m_session(session)
     , m_enabled(false)
     , m_state(nullptr)
     , m_frontend(nullptr)
-    , m_isolate(debugger->isolate())
+    , m_isolate(m_debugger->isolate())
     , m_breakReason(protocol::Debugger::Paused::ReasonEnum::Other)
     , m_scheduledDebuggerStep(NoStep)
     , m_skipNextDebuggerStepOut(false)
@@ -182,13 +176,11 @@
     , m_skipAllPauses(false)
     , m_maxAsyncCallStackDepth(0)
 {
-    m_connection->setDebuggerAgent(this);
     clearBreakDetails();
 }
 
 V8DebuggerAgentImpl::~V8DebuggerAgentImpl()
 {
-    m_connection->setDebuggerAgent(nullptr);
 }
 
 bool V8DebuggerAgentImpl::checkEnabled(ErrorString* errorString)
@@ -204,7 +196,13 @@
     // debugger().addListener may result in reporting all parsed scripts to
     // the agent so it should already be in enabled state by then.
     m_enabled = true;
-    debugger().addDebuggerAgent(m_connection->contextGroupId(), this);
+    debugger().debuggerAgentEnabled();
+
+    protocol::Vector<V8DebuggerParsedScript> compiledScripts;
+    debugger().getCompiledScripts(m_session->contextGroupId(), compiledScripts);
+    for (size_t i = 0; i < compiledScripts.size(); i++)
+        didParseSource(compiledScripts[i]);
+
     // FIXME(WK44513): breakpoints activated flag should be synchronized between all front-ends
     debugger().setBreakpointsActivated(true);
 }
@@ -233,7 +231,9 @@
     m_state->setNumber(DebuggerAgentState::pauseOnExceptionsState, V8DebuggerImpl::DontPauseOnExceptions);
     m_state->setNumber(DebuggerAgentState::asyncCallStackDepth, 0);
 
-    debugger().removeDebuggerAgent(m_connection->contextGroupId());
+    if (!m_pausedContext.IsEmpty())
+        debugger().continueProgram();
+    debugger().debuggerAgentDisabled();
     m_pausedContext.Reset();
     JavaScriptCallFrames emptyCallFrames;
     m_pausedCallFrames.swap(emptyCallFrames);
@@ -629,7 +629,7 @@
     OwnPtr<RemoteCallFrameId> remoteId = RemoteCallFrameId::parse(errorString, callFrameId);
     if (!remoteId)
         return;
-    InjectedScript* injectedScript = m_connection->findInjectedScript(errorString, remoteId.get());
+    InjectedScript* injectedScript = m_session->findInjectedScript(errorString, remoteId.get());
     if (!injectedScript)
         return;
 
@@ -677,7 +677,7 @@
     OwnPtr<RemoteObjectId> remoteId = RemoteObjectId::parse(errorString, functionId);
     if (!remoteId)
         return;
-    InjectedScript* injectedScript = m_connection->findInjectedScript(errorString, remoteId.get());
+    InjectedScript* injectedScript = m_session->findInjectedScript(errorString, remoteId.get());
     if (!injectedScript)
         return;
 
@@ -726,7 +726,7 @@
     OwnPtr<RemoteObjectId> remoteId = RemoteObjectId::parse(errorString, objectId);
     if (!remoteId)
         return;
-    InjectedScript* injectedScript = m_connection->findInjectedScript(errorString, remoteId.get());
+    InjectedScript* injectedScript = m_session->findInjectedScript(errorString, remoteId.get());
     if (!injectedScript)
         return;
 
@@ -766,7 +766,7 @@
     OwnPtr<RemoteObjectId> remoteId = RemoteObjectId::parse(errorString, objectId);
     if (!remoteId)
         return;
-    InjectedScript* injectedScript = m_connection->findInjectedScript(errorString, remoteId.get());
+    InjectedScript* injectedScript = m_session->findInjectedScript(errorString, remoteId.get());
     if (!injectedScript)
         return;
 
@@ -877,7 +877,7 @@
         return;
     m_scheduledDebuggerStep = NoStep;
     m_steppingFromFramework = false;
-    m_connection->releaseObjectGroup(V8DebuggerAgentImpl::backtraceObjectGroup);
+    m_session->releaseObjectGroup(V8DebuggerAgentImpl::backtraceObjectGroup);
     debugger().continueProgram();
 }
 
@@ -893,7 +893,7 @@
     }
     m_scheduledDebuggerStep = StepOver;
     m_steppingFromFramework = isTopPausedCallFrameBlackboxed();
-    m_connection->releaseObjectGroup(V8DebuggerAgentImpl::backtraceObjectGroup);
+    m_session->releaseObjectGroup(V8DebuggerAgentImpl::backtraceObjectGroup);
     debugger().stepOverStatement();
 }
 
@@ -903,7 +903,7 @@
         return;
     m_scheduledDebuggerStep = StepInto;
     m_steppingFromFramework = isTopPausedCallFrameBlackboxed();
-    m_connection->releaseObjectGroup(V8DebuggerAgentImpl::backtraceObjectGroup);
+    m_session->releaseObjectGroup(V8DebuggerAgentImpl::backtraceObjectGroup);
     debugger().stepIntoStatement();
 }
 
@@ -915,7 +915,7 @@
     m_skipNextDebuggerStepOut = false;
     m_recursionLevelForStepOut = 1;
     m_steppingFromFramework = isTopPausedCallFrameBlackboxed();
-    m_connection->releaseObjectGroup(V8DebuggerAgentImpl::backtraceObjectGroup);
+    m_session->releaseObjectGroup(V8DebuggerAgentImpl::backtraceObjectGroup);
     debugger().stepOutOfFunction();
 }
 
@@ -963,7 +963,7 @@
     OwnPtr<RemoteCallFrameId> remoteId = RemoteCallFrameId::parse(errorString, callFrameId);
     if (!remoteId)
         return;
-    InjectedScript* injectedScript = m_connection->findInjectedScript(errorString, remoteId.get());
+    InjectedScript* injectedScript = m_session->findInjectedScript(errorString, remoteId.get());
     if (!injectedScript)
         return;
 
@@ -993,7 +993,7 @@
     v8::MaybeLocal<v8::Value> maybeResultValue = m_pausedCallFrames[frameOrdinal].get()->evaluate(toV8String(injectedScript->isolate(), expression));
 
     // InjectedScript may be gone after any evaluate call - find it again.
-    injectedScript = m_connection->findInjectedScript(errorString, remoteId.get());
+    injectedScript = m_session->findInjectedScript(errorString, remoteId.get());
     if (!injectedScript)
         return;
 
@@ -1021,7 +1021,7 @@
     OwnPtr<RemoteCallFrameId> remoteId = RemoteCallFrameId::parse(errorString, callFrameId);
     if (!remoteId)
         return;
-    InjectedScript* injectedScript = m_connection->findInjectedScript(errorString, remoteId.get());
+    InjectedScript* injectedScript = m_session->findInjectedScript(errorString, remoteId.get());
     if (!injectedScript)
         return;
 
@@ -1216,7 +1216,7 @@
     if (m_pausedContext.IsEmpty() || !m_pausedCallFrames.size())
         return Array<CallFrame>::create();
     ErrorString ignored;
-    InjectedScript* topFrameInjectedScript = m_connection->findInjectedScript(&ignored, V8Debugger::contextId(m_pausedContext.Get(m_isolate)));
+    InjectedScript* topFrameInjectedScript = m_session->findInjectedScript(&ignored, V8Debugger::contextId(m_pausedContext.Get(m_isolate)));
     if (!topFrameInjectedScript) {
         // Context has been reported as removed while on pause.
         return Array<CallFrame>::create();
@@ -1236,7 +1236,7 @@
             return Array<CallFrame>::create();
 
         int contextId = currentCallFrame->contextId();
-        InjectedScript* injectedScript = contextId ? m_connection->findInjectedScript(&ignored, contextId) : nullptr;
+        InjectedScript* injectedScript = contextId ? m_session->findInjectedScript(&ignored, contextId) : nullptr;
         if (!injectedScript)
             injectedScript = topFrameInjectedScript;
 
@@ -1383,7 +1383,7 @@
 
     if (!exception.IsEmpty()) {
         ErrorString ignored;
-        InjectedScript* injectedScript = m_connection->findInjectedScript(&ignored, V8Debugger::contextId(context));
+        InjectedScript* injectedScript = m_session->findInjectedScript(&ignored, V8Debugger::contextId(context));
         if (injectedScript) {
             m_breakReason = isPromiseRejection ? protocol::Debugger::Paused::ReasonEnum::PromiseRejection : protocol::Debugger::Paused::ReasonEnum::Exception;
             ErrorString errorString;
diff --git a/third_party/WebKit/Source/platform/v8_inspector/V8DebuggerAgentImpl.h b/third_party/WebKit/Source/platform/v8_inspector/V8DebuggerAgentImpl.h
index 9d10d488..1bd7e13 100644
--- a/third_party/WebKit/Source/platform/v8_inspector/V8DebuggerAgentImpl.h
+++ b/third_party/WebKit/Source/platform/v8_inspector/V8DebuggerAgentImpl.h
@@ -16,7 +16,7 @@
 
 class JavaScriptCallFrame;
 class PromiseTracker;
-class V8InspectorConnectionImpl;
+class V8InspectorSessionImpl;
 class V8StackTraceImpl;
 
 namespace protocol {
@@ -42,7 +42,7 @@
         MonitorCommandBreakpointSource
     };
 
-    V8DebuggerAgentImpl(V8InspectorConnectionImpl*, V8DebuggerImpl*);
+    explicit V8DebuggerAgentImpl(V8InspectorSessionImpl*);
     ~V8DebuggerAgentImpl() override;
 
     void setInspectorState(protocol::DictionaryValue*) override;
@@ -209,7 +209,7 @@
     };
 
     V8DebuggerImpl* m_debugger;
-    V8InspectorConnectionImpl* m_connection;
+    V8InspectorSessionImpl* m_session;
     bool m_enabled;
     protocol::DictionaryValue* m_state;
     protocol::Frontend::Debugger* m_frontend;
diff --git a/third_party/WebKit/Source/platform/v8_inspector/V8DebuggerImpl.cpp b/third_party/WebKit/Source/platform/v8_inspector/V8DebuggerImpl.cpp
index 72e957ca..53f4716 100644
--- a/third_party/WebKit/Source/platform/v8_inspector/V8DebuggerImpl.cpp
+++ b/third_party/WebKit/Source/platform/v8_inspector/V8DebuggerImpl.cpp
@@ -36,7 +36,7 @@
 #include "platform/v8_inspector/InspectedContext.h"
 #include "platform/v8_inspector/ScriptBreakpoint.h"
 #include "platform/v8_inspector/V8DebuggerAgentImpl.h"
-#include "platform/v8_inspector/V8InspectorConnectionImpl.h"
+#include "platform/v8_inspector/V8InspectorSessionImpl.h"
 #include "platform/v8_inspector/V8RuntimeAgentImpl.h"
 #include "platform/v8_inspector/V8StackTraceImpl.h"
 #include "platform/v8_inspector/V8StringUtil.h"
@@ -75,6 +75,7 @@
 V8DebuggerImpl::V8DebuggerImpl(v8::Isolate* isolate, V8DebuggerClient* client)
     : m_isolate(isolate)
     , m_client(client)
+    , m_enabledAgentsCount(0)
     , m_breakpointsActivated(true)
     , m_runningNestedMessageLoop(false)
 {
@@ -138,63 +139,31 @@
     return dataString.substring(0, commaPos).toInt();
 }
 
-void V8DebuggerImpl::addDebuggerAgent(int contextGroupId, V8DebuggerAgentImpl* agent)
+void V8DebuggerImpl::debuggerAgentEnabled()
 {
-    ASSERT(contextGroupId);
-    ASSERT(!m_debuggerAgentsMap.contains(contextGroupId));
-    if (m_debuggerAgentsMap.isEmpty())
+    if (!m_enabledAgentsCount++)
         enable();
-    m_debuggerAgentsMap.set(contextGroupId, agent);
-
-    protocol::Vector<V8DebuggerParsedScript> compiledScripts;
-    getCompiledScripts(contextGroupId, compiledScripts);
-    for (size_t i = 0; i < compiledScripts.size(); i++)
-        agent->didParseSource(compiledScripts[i]);
 }
 
-void V8DebuggerImpl::removeDebuggerAgent(int contextGroupId)
+void V8DebuggerImpl::debuggerAgentDisabled()
 {
-    ASSERT(contextGroupId);
-    if (!m_debuggerAgentsMap.contains(contextGroupId))
-        return;
-
-    if (!m_pausedContext.IsEmpty() && getGroupId(m_pausedContext) == contextGroupId)
-        continueProgram();
-
-    m_debuggerAgentsMap.remove(contextGroupId);
-
-    if (m_debuggerAgentsMap.isEmpty())
+    if (!--m_enabledAgentsCount)
         disable();
 }
 
-V8DebuggerAgentImpl* V8DebuggerImpl::getDebuggerAgentForContext(v8::Local<v8::Context> context)
+V8DebuggerAgentImpl* V8DebuggerImpl::findEnabledDebuggerAgent(int contextGroupId)
 {
-    int groupId = getGroupId(context);
-    if (!groupId)
+    if (!contextGroupId)
         return nullptr;
-    return m_debuggerAgentsMap.get(groupId);
+    V8InspectorSessionImpl* session = m_sessions.get(contextGroupId);
+    if (session && session->debuggerAgentImpl()->enabled())
+        return session->debuggerAgentImpl();
+    return nullptr;
 }
 
-void V8DebuggerImpl::addRuntimeAgent(int contextGroupId, V8RuntimeAgentImpl* agent)
+V8DebuggerAgentImpl* V8DebuggerImpl::findEnabledDebuggerAgent(v8::Local<v8::Context> context)
 {
-    ASSERT(contextGroupId);
-    ASSERT(!m_runtimeAgentsMap.contains(contextGroupId));
-    m_runtimeAgentsMap.set(contextGroupId, agent);
-}
-
-void V8DebuggerImpl::removeRuntimeAgent(int contextGroupId)
-{
-    ASSERT(contextGroupId);
-    if (m_runtimeAgentsMap.contains(contextGroupId))
-        m_runtimeAgentsMap.remove(contextGroupId);
-}
-
-V8RuntimeAgentImpl* V8DebuggerImpl::getRuntimeAgentForContext(v8::Local<v8::Context> context)
-{
-    int groupId = getGroupId(context);
-    if (!groupId)
-        return nullptr;
-    return m_runtimeAgentsMap.get(groupId);
+    return findEnabledDebuggerAgent(getGroupId(context));
 }
 
 void V8DebuggerImpl::getCompiledScripts(int contextGroupId, protocol::Vector<V8DebuggerParsedScript>& result)
@@ -508,7 +477,7 @@
     if (m_runningNestedMessageLoop)
         return;
 
-    V8DebuggerAgentImpl* agent = getDebuggerAgentForContext(pausedContext);
+    V8DebuggerAgentImpl* agent = findEnabledDebuggerAgent(pausedContext);
     if (!agent)
         return;
 
@@ -531,7 +500,7 @@
         ASSERT(groupId);
         m_client->runMessageLoopOnPause(groupId);
         // The agent may have been removed in the nested loop.
-        agent = getDebuggerAgentForContext(pausedContext);
+        agent = findEnabledDebuggerAgent(pausedContext);
         if (agent)
             agent->didContinue();
         m_runningNestedMessageLoop = false;
@@ -576,7 +545,7 @@
     v8::Local<v8::Context> eventContext = eventDetails.GetEventContext();
     ASSERT(!eventContext.IsEmpty());
 
-    V8DebuggerAgentImpl* agent = getDebuggerAgentForContext(eventContext);
+    V8DebuggerAgentImpl* agent = findEnabledDebuggerAgent(eventContext);
     if (agent) {
         v8::HandleScope scope(m_isolate);
         if (event == v8::AfterCompile || event == v8::CompileError) {
@@ -712,13 +681,11 @@
 
     v8::MicrotasksScope microtasksScope(m_isolate, v8::MicrotasksScope::kRunMicrotasks);
     int groupId = getGroupId(context);
-    V8DebuggerAgentImpl* agent = groupId ? m_debuggerAgentsMap.get(groupId) : nullptr;
-    if (agent)
+    if (V8DebuggerAgentImpl* agent = findEnabledDebuggerAgent(groupId))
         agent->willExecuteScript(script->GetUnboundScript()->GetId());
     v8::MaybeLocal<v8::Value> result = script->Run(context);
     // Get agent from the map again, since it could have detached during script execution.
-    agent = groupId ? m_debuggerAgentsMap.get(groupId) : nullptr;
-    if (agent)
+    if (V8DebuggerAgentImpl* agent = findEnabledDebuggerAgent(groupId))
         agent->didExecuteScript();
     return result;
 }
@@ -731,13 +698,11 @@
 
     v8::MicrotasksScope microtasksScope(m_isolate, v8::MicrotasksScope::kRunMicrotasks);
     int groupId = getGroupId(context);
-    V8DebuggerAgentImpl* agent = groupId ? m_debuggerAgentsMap.get(groupId) : nullptr;
-    if (agent)
+    if (V8DebuggerAgentImpl* agent = findEnabledDebuggerAgent(groupId))
         agent->willExecuteScript(function->ScriptId());
     v8::MaybeLocal<v8::Value> result = function->Call(context, receiver, argc, info);
     // Get agent from the map again, since it could have detached during script execution.
-    agent = groupId ? m_debuggerAgentsMap.get(groupId) : nullptr;
-    if (agent)
+    if (V8DebuggerAgentImpl* agent = findEnabledDebuggerAgent(groupId))
         agent->didExecuteScript();
     return result;
 }
@@ -773,10 +738,24 @@
 
 PassOwnPtr<V8StackTrace> V8DebuggerImpl::createStackTrace(v8::Local<v8::StackTrace> stackTrace, size_t maxStackSize)
 {
-    V8DebuggerAgentImpl* agent = getDebuggerAgentForContext(m_isolate->GetCurrentContext());
+    V8DebuggerAgentImpl* agent = findEnabledDebuggerAgent(m_isolate->GetCurrentContext());
     return V8StackTraceImpl::create(agent, stackTrace, maxStackSize);
 }
 
+PassOwnPtr<V8InspectorSession> V8DebuggerImpl::connect(int contextGroupId)
+{
+    ASSERT(!m_sessions.contains(contextGroupId));
+    OwnPtr<V8InspectorSessionImpl> session = V8InspectorSessionImpl::create(this, contextGroupId);
+    m_sessions.set(contextGroupId, session.get());
+    return session.release();
+}
+
+void V8DebuggerImpl::disconnect(V8InspectorSessionImpl* session)
+{
+    ASSERT(m_sessions.contains(session->contextGroupId()));
+    m_sessions.remove(session->contextGroupId());
+}
+
 void V8DebuggerImpl::contextCreated(const V8ContextInfo& info)
 {
     ASSERT(info.context->GetIsolate() == m_isolate);
@@ -795,9 +774,8 @@
     InspectedContext* inspectedContext = contextOwner.get();
     m_contexts.get(info.contextGroupId)->set(contextId, contextOwner.release());
 
-    V8RuntimeAgentImpl* agent = getRuntimeAgentForContext(info.context);
-    if (agent)
-        agent->reportExecutionContextCreated(inspectedContext);
+    if (V8InspectorSessionImpl* session = m_sessions.get(info.contextGroupId))
+        session->runtimeAgentImpl()->reportExecutionContextCreated(inspectedContext);
 }
 
 void V8DebuggerImpl::contextDestroyed(v8::Local<v8::Context> context)
@@ -808,9 +786,8 @@
         return;
 
     InspectedContext* inspectedContext = m_contexts.get(contextGroupId)->get(contextId);
-    V8RuntimeAgentImpl* agent = getRuntimeAgentForContext(context);
-    if (agent)
-        agent->reportExecutionContextDestroyed(inspectedContext);
+    if (V8InspectorSessionImpl* session = m_sessions.get(contextGroupId))
+        session->runtimeAgentImpl()->reportExecutionContextDestroyed(inspectedContext);
 
     m_contexts.get(contextGroupId)->remove(contextId);
     if (m_contexts.get(contextGroupId)->isEmpty())
@@ -819,19 +796,14 @@
 
 void V8DebuggerImpl::resetContextGroup(int contextGroupId)
 {
-    V8DebuggerAgentImpl* debuggerAgent = m_debuggerAgentsMap.get(contextGroupId);
-    if (debuggerAgent)
-        debuggerAgent->reset();
-    V8RuntimeAgentImpl* runtimeAgent = m_runtimeAgentsMap.get(contextGroupId);
-    if (runtimeAgent)
-        runtimeAgent->reset();
-    if (m_contexts.contains(contextGroupId))
-        m_contexts.remove(contextGroupId);
+    if (V8InspectorSessionImpl* session = m_sessions.get(contextGroupId))
+        session->reset();
+    m_contexts.remove(contextGroupId);
 }
 
 PassOwnPtr<V8StackTrace> V8DebuggerImpl::captureStackTrace(size_t maxStackSize)
 {
-    V8DebuggerAgentImpl* agent = getDebuggerAgentForContext(m_isolate->GetCurrentContext());
+    V8DebuggerAgentImpl* agent = findEnabledDebuggerAgent(m_isolate->GetCurrentContext());
     return V8StackTraceImpl::capture(agent, maxStackSize);
 }
 
@@ -847,6 +819,8 @@
     if (!m_contexts.contains(contextGroupId) || !m_contexts.get(contextGroupId)->contains(contextId))
         return;
     m_contexts.get(contextGroupId)->remove(contextId);
+    if (m_contexts.get(contextGroupId)->isEmpty())
+        m_contexts.remove(contextGroupId);
 }
 
 const V8DebuggerImpl::ContextByIdMap* V8DebuggerImpl::contextGroup(int contextGroupId)
diff --git a/third_party/WebKit/Source/platform/v8_inspector/V8DebuggerImpl.h b/third_party/WebKit/Source/platform/v8_inspector/V8DebuggerImpl.h
index 5e0c4a5..e85c36c 100644
--- a/third_party/WebKit/Source/platform/v8_inspector/V8DebuggerImpl.h
+++ b/third_party/WebKit/Source/platform/v8_inspector/V8DebuggerImpl.h
@@ -47,6 +47,7 @@
 struct ScriptBreakpoint;
 class InspectedContext;
 class V8DebuggerAgentImpl;
+class V8InspectorSessionImpl;
 class V8RuntimeAgentImpl;
 
 class V8DebuggerImpl : public V8Debugger {
@@ -57,11 +58,6 @@
 
     bool enabled() const;
 
-    void addDebuggerAgent(int contextGroupId, V8DebuggerAgentImpl*);
-    void removeDebuggerAgent(int contextGroupId);
-    void addRuntimeAgent(int contextGroupId, V8RuntimeAgentImpl*);
-    void removeRuntimeAgent(int contextGroupId);
-
     String16 setBreakpoint(const String16& sourceID, const ScriptBreakpoint&, int* actualLineNumber, int* actualColumnNumber, bool interstatementLocation);
     void removeBreakpoint(const String16& breakpointId);
     void setBreakpointsActivated(bool);
@@ -87,6 +83,13 @@
     bool setScriptSource(const String16& sourceID, const String16& newContent, bool preview, ErrorString*, Maybe<protocol::Debugger::SetScriptSourceError>*, JavaScriptCallFrames* newCallFrames, Maybe<bool>* stackChanged);
     JavaScriptCallFrames currentCallFrames(int limit = 0);
 
+    // Each script inherits debug data from v8::Context where it has been compiled.
+    // Only scripts whose debug data matches |contextGroupId| will be reported.
+    // Passing 0 will result in reporting all scripts.
+    void getCompiledScripts(int contextGroupId, protocol::Vector<V8DebuggerParsedScript>&);
+    void debuggerAgentEnabled();
+    void debuggerAgentDisabled();
+
     bool isPaused();
     v8::Local<v8::Context> pausedContext() { return m_pausedContext; }
 
@@ -104,6 +107,7 @@
     v8::Local<v8::Context> regexContext();
 
     // V8Debugger implementation
+    PassOwnPtr<V8InspectorSession> connect(int contextGroupId) override;
     void contextCreated(const V8ContextInfo&) override;
     void contextDestroyed(v8::Local<v8::Context>) override;
     void resetContextGroup(int contextGroupId) override;
@@ -113,16 +117,13 @@
     using ContextByIdMap = protocol::HashMap<int, OwnPtr<InspectedContext>>;
     void discardInspectedContext(int contextGroupId, int contextId);
     const ContextByIdMap* contextGroup(int contextGroupId);
+    void disconnect(V8InspectorSessionImpl*);
 
 private:
     void enable();
     void disable();
-    // Each script inherits debug data from v8::Context where it has been compiled.
-    // Only scripts whose debug data matches |contextGroupId| will be reported.
-    // Passing 0 will result in reporting all scripts.
-    void getCompiledScripts(int contextGroupId, protocol::Vector<V8DebuggerParsedScript>&);
-    V8DebuggerAgentImpl* getDebuggerAgentForContext(v8::Local<v8::Context>);
-    V8RuntimeAgentImpl* getRuntimeAgentForContext(v8::Local<v8::Context>);
+    V8DebuggerAgentImpl* findEnabledDebuggerAgent(int contextGroupId);
+    V8DebuggerAgentImpl* findEnabledDebuggerAgent(v8::Local<v8::Context>);
 
     void compileDebuggerScript();
     v8::MaybeLocal<v8::Value> callDebuggerMethod(const char* functionName, int argc, v8::Local<v8::Value> argv[]);
@@ -145,10 +146,9 @@
     V8DebuggerClient* m_client;
     using ContextsByGroupMap = protocol::HashMap<int, OwnPtr<ContextByIdMap>>;
     ContextsByGroupMap m_contexts;
-    using DebuggerAgentsMap = protocol::HashMap<int, V8DebuggerAgentImpl*>;
-    DebuggerAgentsMap m_debuggerAgentsMap;
-    using RuntimeAgentsMap = protocol::HashMap<int, V8RuntimeAgentImpl*>;
-    RuntimeAgentsMap m_runtimeAgentsMap;
+    using SessionMap = protocol::HashMap<int, V8InspectorSessionImpl*>;
+    SessionMap m_sessions;
+    int m_enabledAgentsCount;
     bool m_breakpointsActivated;
     v8::Global<v8::FunctionTemplate> m_breakProgramCallbackTemplate;
     v8::Global<v8::Object> m_debuggerScript;
diff --git a/third_party/WebKit/Source/platform/v8_inspector/V8HeapProfilerAgentImpl.cpp b/third_party/WebKit/Source/platform/v8_inspector/V8HeapProfilerAgentImpl.cpp
index d236427..58440f7 100644
--- a/third_party/WebKit/Source/platform/v8_inspector/V8HeapProfilerAgentImpl.cpp
+++ b/third_party/WebKit/Source/platform/v8_inspector/V8HeapProfilerAgentImpl.cpp
@@ -6,8 +6,7 @@
 
 #include "platform/v8_inspector/InjectedScript.h"
 #include "platform/v8_inspector/V8DebuggerImpl.h"
-#include "platform/v8_inspector/V8InspectorConnectionImpl.h"
-#include "platform/v8_inspector/V8RuntimeAgentImpl.h"
+#include "platform/v8_inspector/V8InspectorSessionImpl.h"
 #include "platform/v8_inspector/V8StringUtil.h"
 #include "platform/v8_inspector/public/V8DebuggerClient.h"
 #include <v8-profiler.h>
@@ -45,7 +44,7 @@
 
 class GlobalObjectNameResolver final : public v8::HeapProfiler::ObjectNameResolver {
 public:
-    explicit GlobalObjectNameResolver(V8RuntimeAgentImpl* runtimeAgent) : m_offset(0), m_runtimeAgent(runtimeAgent)
+    explicit GlobalObjectNameResolver(V8InspectorSessionImpl* session) : m_offset(0), m_session(session)
     {
         m_strings.resize(10000);
     }
@@ -56,7 +55,7 @@
         if (!contextId)
             return "";
         ErrorString errorString;
-        InjectedScript* injectedScript = m_runtimeAgent->connection()->findInjectedScript(&errorString, contextId);
+        InjectedScript* injectedScript = m_session->findInjectedScript(&errorString, contextId);
         if (!injectedScript)
             return "";
         String16 name = injectedScript->context()->origin();
@@ -76,7 +75,7 @@
 private:
     size_t m_offset;
     protocol::Vector<char> m_strings;
-    V8RuntimeAgentImpl* m_runtimeAgent;
+    V8InspectorSessionImpl* m_session;
 };
 
 class HeapSnapshotOutputStream final : public v8::OutputStream {
@@ -149,14 +148,9 @@
 
 } // namespace
 
-PassOwnPtr<V8HeapProfilerAgent> V8HeapProfilerAgent::create(v8::Isolate* isolate, V8RuntimeAgent* runtimeAgent)
-{
-    return adoptPtr(new V8HeapProfilerAgentImpl(isolate, runtimeAgent));
-}
-
-V8HeapProfilerAgentImpl::V8HeapProfilerAgentImpl(v8::Isolate* isolate, V8RuntimeAgent* runtimeAgent)
-    : m_isolate(isolate)
-    , m_runtimeAgent(static_cast<V8RuntimeAgentImpl*>(runtimeAgent))
+V8HeapProfilerAgentImpl::V8HeapProfilerAgentImpl(V8InspectorSessionImpl* session)
+    : m_session(session)
+    , m_isolate(session->debugger()->isolate())
 {
 }
 
@@ -236,7 +230,7 @@
     if (reportProgress.fromMaybe(false))
         progress = adoptPtr(new HeapSnapshotProgress(m_frontend));
 
-    GlobalObjectNameResolver resolver(m_runtimeAgent);
+    GlobalObjectNameResolver resolver(m_session);
     const v8::HeapSnapshot* snapshot = profiler->TakeHeapSnapshot(progress.get(), &resolver);
     if (!snapshot) {
         *errorString = "Failed to take heap snapshot";
@@ -262,7 +256,7 @@
         *error = "Object is not available";
         return;
     }
-    *result = m_runtimeAgent->wrapObject(heapObject->CreationContext(), heapObject, objectGroup.fromMaybe(""));
+    *result = m_session->runtimeAgent()->wrapObject(heapObject->CreationContext(), heapObject, objectGroup.fromMaybe(""));
     if (!result)
         *error = "Object is not available";
 }
@@ -275,13 +269,13 @@
         *errorString = "Invalid heap snapshot object id";
         return;
     }
-    m_runtimeAgent->addInspectedObject(adoptPtr(new InspectableHeapObject(id)));
+    m_session->runtimeAgent()->addInspectedObject(adoptPtr(new InspectableHeapObject(id)));
 }
 
 void V8HeapProfilerAgentImpl::getHeapObjectId(ErrorString* errorString, const String16& objectId, String16* heapSnapshotObjectId)
 {
     v8::HandleScope handles(m_isolate);
-    v8::Local<v8::Value> value = m_runtimeAgent->findObject(errorString, objectId);
+    v8::Local<v8::Value> value = m_session->runtimeAgent()->findObject(errorString, objectId);
     if (value.IsEmpty() || value->IsUndefined())
         return;
 
@@ -295,7 +289,7 @@
         return;
     HeapStatsStream stream(m_frontend);
     v8::SnapshotObjectId lastSeenObjectId = m_isolate->GetHeapProfiler()->GetHeapStats(&stream);
-    m_frontend->lastSeenObjectId(lastSeenObjectId, m_runtimeAgent->debugger()->client()->currentTimeMS());
+    m_frontend->lastSeenObjectId(lastSeenObjectId, m_session->debugger()->client()->currentTimeMS());
 }
 
 void V8HeapProfilerAgentImpl::startTrackingHeapObjectsInternal(bool trackAllocations)
diff --git a/third_party/WebKit/Source/platform/v8_inspector/V8HeapProfilerAgentImpl.h b/third_party/WebKit/Source/platform/v8_inspector/V8HeapProfilerAgentImpl.h
index cb0f196..86a4976 100644
--- a/third_party/WebKit/Source/platform/v8_inspector/V8HeapProfilerAgentImpl.h
+++ b/third_party/WebKit/Source/platform/v8_inspector/V8HeapProfilerAgentImpl.h
@@ -10,14 +10,14 @@
 
 namespace blink {
 
-class V8RuntimeAgentImpl;
+class V8InspectorSessionImpl;
 
 using protocol::Maybe;
 
 class V8HeapProfilerAgentImpl : public V8HeapProfilerAgent {
     PROTOCOL_DISALLOW_COPY(V8HeapProfilerAgentImpl);
 public:
-    explicit V8HeapProfilerAgentImpl(v8::Isolate*, V8RuntimeAgent*);
+    explicit V8HeapProfilerAgentImpl(V8InspectorSessionImpl*);
     ~V8HeapProfilerAgentImpl() override;
 
     void setInspectorState(protocol::DictionaryValue* state) override { m_state = state; }
@@ -48,8 +48,8 @@
     void startTrackingHeapObjectsInternal(bool trackAllocations);
     void stopTrackingHeapObjectsInternal();
 
+    V8InspectorSessionImpl* m_session;
     v8::Isolate* m_isolate;
-    V8RuntimeAgentImpl* m_runtimeAgent;
     protocol::Frontend::HeapProfiler* m_frontend;
     protocol::DictionaryValue* m_state;
 };
diff --git a/third_party/WebKit/Source/platform/v8_inspector/V8InspectorConnectionImpl.cpp b/third_party/WebKit/Source/platform/v8_inspector/V8InspectorSessionImpl.cpp
similarity index 65%
rename from third_party/WebKit/Source/platform/v8_inspector/V8InspectorConnectionImpl.cpp
rename to third_party/WebKit/Source/platform/v8_inspector/V8InspectorSessionImpl.cpp
index 73f35ed..70eeef74 100644
--- a/third_party/WebKit/Source/platform/v8_inspector/V8InspectorConnectionImpl.cpp
+++ b/third_party/WebKit/Source/platform/v8_inspector/V8InspectorSessionImpl.cpp
@@ -2,7 +2,7 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#include "platform/v8_inspector/V8InspectorConnectionImpl.h"
+#include "platform/v8_inspector/V8InspectorSessionImpl.h"
 
 #include "platform/v8_inspector/InjectedScript.h"
 #include "platform/v8_inspector/InjectedScriptHost.h"
@@ -10,35 +10,67 @@
 #include "platform/v8_inspector/RemoteObjectId.h"
 #include "platform/v8_inspector/V8DebuggerAgentImpl.h"
 #include "platform/v8_inspector/V8DebuggerImpl.h"
+#include "platform/v8_inspector/V8HeapProfilerAgentImpl.h"
+#include "platform/v8_inspector/V8ProfilerAgentImpl.h"
 #include "platform/v8_inspector/V8RuntimeAgentImpl.h"
 #include "platform/v8_inspector/public/V8ContextInfo.h"
 #include "platform/v8_inspector/public/V8DebuggerClient.h"
 
 namespace blink {
 
-PassOwnPtr<V8InspectorConnectionImpl> V8InspectorConnectionImpl::create(V8DebuggerImpl* debugger, int contextGroupId)
+PassOwnPtr<V8InspectorSessionImpl> V8InspectorSessionImpl::create(V8DebuggerImpl* debugger, int contextGroupId)
 {
-    return adoptPtr(new V8InspectorConnectionImpl(debugger, contextGroupId));
+    return adoptPtr(new V8InspectorSessionImpl(debugger, contextGroupId));
 }
 
-V8InspectorConnectionImpl::V8InspectorConnectionImpl(V8DebuggerImpl* debugger, int contextGroupId)
+V8InspectorSessionImpl::V8InspectorSessionImpl(V8DebuggerImpl* debugger, int contextGroupId)
     : m_contextGroupId(contextGroupId)
     , m_debugger(debugger)
     , m_injectedScriptHost(InjectedScriptHost::create(debugger, this))
     , m_customObjectFormatterEnabled(false)
-    , m_debuggerAgent(nullptr)
+    , m_runtimeAgent(adoptPtr(new V8RuntimeAgentImpl(this)))
+    , m_debuggerAgent(adoptPtr(new V8DebuggerAgentImpl(this)))
+    , m_heapProfilerAgent(adoptPtr(new V8HeapProfilerAgentImpl(this)))
+    , m_profilerAgent(adoptPtr(new V8ProfilerAgentImpl(this)))
     , m_inspectCallback(nullptr)
     , m_clearConsoleCallback(nullptr)
 {
 }
 
-V8InspectorConnectionImpl::~V8InspectorConnectionImpl()
+V8InspectorSessionImpl::~V8InspectorSessionImpl()
 {
-    resetInjectedScripts();
-    ASSERT(!m_debuggerAgent);
+    discardInjectedScripts();
+    m_debugger->disconnect(this);
 }
 
-void V8InspectorConnectionImpl::resetInjectedScripts()
+V8DebuggerAgent* V8InspectorSessionImpl::debuggerAgent()
+{
+    return m_debuggerAgent.get();
+}
+
+V8HeapProfilerAgent* V8InspectorSessionImpl::heapProfilerAgent()
+{
+    return m_heapProfilerAgent.get();
+}
+
+V8ProfilerAgent* V8InspectorSessionImpl::profilerAgent()
+{
+    return m_profilerAgent.get();
+}
+
+V8RuntimeAgent* V8InspectorSessionImpl::runtimeAgent()
+{
+    return m_runtimeAgent.get();
+}
+
+void V8InspectorSessionImpl::reset()
+{
+    m_debuggerAgent->reset();
+    m_runtimeAgent->reset();
+    discardInjectedScripts();
+}
+
+void V8InspectorSessionImpl::discardInjectedScripts()
 {
     m_injectedScriptHost->clearInspectedObjects();
     const V8DebuggerImpl::ContextByIdMap* contexts = m_debugger->contextGroup(m_contextGroupId);
@@ -55,7 +87,7 @@
     }
 }
 
-InjectedScript* V8InspectorConnectionImpl::findInjectedScript(ErrorString* errorString, int contextId)
+InjectedScript* V8InspectorSessionImpl::findInjectedScript(ErrorString* errorString, int contextId)
 {
     const V8DebuggerImpl::ContextByIdMap* contexts = m_debugger->contextGroup(m_contextGroupId);
     if (!contexts || !contexts->contains(contextId)) {
@@ -76,17 +108,17 @@
     return context->getInjectedScript();
 }
 
-InjectedScript* V8InspectorConnectionImpl::findInjectedScript(ErrorString* errorString, RemoteObjectIdBase* objectId)
+InjectedScript* V8InspectorSessionImpl::findInjectedScript(ErrorString* errorString, RemoteObjectIdBase* objectId)
 {
     return objectId ? findInjectedScript(errorString, objectId->contextId()) : nullptr;
 }
 
-void V8InspectorConnectionImpl::addInspectedObject(PassOwnPtr<V8RuntimeAgent::Inspectable> inspectable)
+void V8InspectorSessionImpl::addInspectedObject(PassOwnPtr<V8RuntimeAgent::Inspectable> inspectable)
 {
     m_injectedScriptHost->addInspectedObject(inspectable);
 }
 
-void V8InspectorConnectionImpl::releaseObjectGroup(const String16& objectGroup)
+void V8InspectorSessionImpl::releaseObjectGroup(const String16& objectGroup)
 {
     const V8DebuggerImpl::ContextByIdMap* contexts = m_debugger->contextGroup(m_contextGroupId);
     if (!contexts)
@@ -105,7 +137,7 @@
     }
 }
 
-void V8InspectorConnectionImpl::setCustomObjectFormatterEnabled(bool enabled)
+void V8InspectorSessionImpl::setCustomObjectFormatterEnabled(bool enabled)
 {
     m_customObjectFormatterEnabled = enabled;
     const V8DebuggerImpl::ContextByIdMap* contexts = m_debugger->contextGroup(m_contextGroupId);
@@ -118,7 +150,7 @@
     }
 }
 
-void V8InspectorConnectionImpl::reportAllContexts(V8RuntimeAgentImpl* agent)
+void V8InspectorSessionImpl::reportAllContexts(V8RuntimeAgentImpl* agent)
 {
     const V8DebuggerImpl::ContextByIdMap* contexts = m_debugger->contextGroup(m_contextGroupId);
     if (!contexts)
diff --git a/third_party/WebKit/Source/platform/v8_inspector/V8InspectorConnectionImpl.h b/third_party/WebKit/Source/platform/v8_inspector/V8InspectorSessionImpl.h
similarity index 63%
rename from third_party/WebKit/Source/platform/v8_inspector/V8InspectorConnectionImpl.h
rename to third_party/WebKit/Source/platform/v8_inspector/V8InspectorSessionImpl.h
index 5abc95d6..c8b47ce 100644
--- a/third_party/WebKit/Source/platform/v8_inspector/V8InspectorConnectionImpl.h
+++ b/third_party/WebKit/Source/platform/v8_inspector/V8InspectorSessionImpl.h
@@ -2,13 +2,14 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#ifndef V8InspectorConnectionImpl_h
-#define V8InspectorConnectionImpl_h
+#ifndef V8InspectorSessionImpl_h
+#define V8InspectorSessionImpl_h
 
 #include "platform/inspector_protocol/Allocator.h"
 #include "platform/inspector_protocol/Collections.h"
 #include "platform/inspector_protocol/String16.h"
 #include "platform/inspector_protocol/TypeBuilder.h"
+#include "platform/v8_inspector/public/V8InspectorSession.h"
 #include "platform/v8_inspector/public/V8RuntimeAgent.h"
 #include "wtf/PassOwnPtr.h"
 
@@ -18,47 +19,57 @@
 
 class InjectedScript;
 class InjectedScriptHost;
-class InjectedScriptNative;
-class InspectedContext;
 class RemoteObjectIdBase;
-class V8ContextInfo;
 class V8DebuggerAgentImpl;
 class V8DebuggerImpl;
+class V8HeapProfilerAgentImpl;
+class V8ProfilerAgentImpl;
 class V8RuntimeAgentImpl;
 
-class V8InspectorConnectionImpl {
-    PROTOCOL_DISALLOW_COPY(V8InspectorConnectionImpl);
+class V8InspectorSessionImpl : public V8InspectorSession {
+    PROTOCOL_DISALLOW_COPY(V8InspectorSessionImpl);
 public:
-    static PassOwnPtr<V8InspectorConnectionImpl> create(V8DebuggerImpl*, int contextGroupId);
-    ~V8InspectorConnectionImpl();
+    static PassOwnPtr<V8InspectorSessionImpl> create(V8DebuggerImpl*, int contextGroupId);
+    ~V8InspectorSessionImpl();
 
     V8DebuggerImpl* debugger() const { return m_debugger; }
+    V8DebuggerAgentImpl* debuggerAgentImpl() { return m_debuggerAgent.get(); }
+    V8RuntimeAgentImpl* runtimeAgentImpl() { return m_runtimeAgent.get(); }
     int contextGroupId() const { return m_contextGroupId; }
 
     InjectedScript* findInjectedScript(ErrorString*, int contextId);
     InjectedScript* findInjectedScript(ErrorString*, RemoteObjectIdBase*);
-    void resetInjectedScripts();
+    void reset();
+    void discardInjectedScripts();
     void reportAllContexts(V8RuntimeAgentImpl*);
     void addInspectedObject(PassOwnPtr<V8RuntimeAgent::Inspectable>);
     void releaseObjectGroup(const String16& objectGroup);
     void setCustomObjectFormatterEnabled(bool);
 
-    // TODO(dgozman): remove these once runtime and debugger agent have the same lifetime.
-    void setDebuggerAgent(V8DebuggerAgentImpl* agent) { m_debuggerAgent = agent; }
-    V8DebuggerAgentImpl* debuggerAgent() { return m_debuggerAgent; }
+    // V8InspectorSession implementation.
+    V8DebuggerAgent* debuggerAgent() override;
+    V8HeapProfilerAgent* heapProfilerAgent() override;
+    V8ProfilerAgent* profilerAgent() override;
+    V8RuntimeAgent* runtimeAgent() override;
+
     void setClearConsoleCallback(PassOwnPtr<V8RuntimeAgent::ClearConsoleCallback> callback) { m_clearConsoleCallback = callback; }
     V8RuntimeAgent::ClearConsoleCallback* clearConsoleCallback() { return m_clearConsoleCallback.get(); }
     void setInspectObjectCallback(PassOwnPtr<V8RuntimeAgent::InspectCallback> callback) { m_inspectCallback = callback; }
     V8RuntimeAgent::InspectCallback* inspectCallback() { return m_inspectCallback.get(); }
 
 private:
-    friend class InspectedContext;
-    V8InspectorConnectionImpl(V8DebuggerImpl*, int contextGroupId);
+    V8InspectorSessionImpl(V8DebuggerImpl*, int contextGroupId);
+
     int m_contextGroupId;
     V8DebuggerImpl* m_debugger;
     OwnPtr<InjectedScriptHost> m_injectedScriptHost;
     bool m_customObjectFormatterEnabled;
-    V8DebuggerAgentImpl* m_debuggerAgent;
+
+    OwnPtr<V8RuntimeAgentImpl> m_runtimeAgent;
+    OwnPtr<V8DebuggerAgentImpl> m_debuggerAgent;
+    OwnPtr<V8HeapProfilerAgentImpl> m_heapProfilerAgent;
+    OwnPtr<V8ProfilerAgentImpl> m_profilerAgent;
+
     OwnPtr<V8RuntimeAgent::InspectCallback> m_inspectCallback;
     OwnPtr<V8RuntimeAgent::ClearConsoleCallback> m_clearConsoleCallback;
 };
diff --git a/third_party/WebKit/Source/platform/v8_inspector/V8ProfilerAgentImpl.cpp b/third_party/WebKit/Source/platform/v8_inspector/V8ProfilerAgentImpl.cpp
index 0152959..c1604f8 100644
--- a/third_party/WebKit/Source/platform/v8_inspector/V8ProfilerAgentImpl.cpp
+++ b/third_party/WebKit/Source/platform/v8_inspector/V8ProfilerAgentImpl.cpp
@@ -6,6 +6,7 @@
 
 #include "platform/v8_inspector/Atomics.h"
 #include "platform/v8_inspector/V8DebuggerImpl.h"
+#include "platform/v8_inspector/V8InspectorSessionImpl.h"
 #include "platform/v8_inspector/V8StackTraceImpl.h"
 #include "platform/v8_inspector/V8StringUtil.h"
 #include <v8-profiler.h>
@@ -119,13 +120,8 @@
     String16 m_title;
 };
 
-PassOwnPtr<V8ProfilerAgent> V8ProfilerAgent::create(V8Debugger* debugger)
-{
-    return adoptPtr(new V8ProfilerAgentImpl(debugger));
-}
-
-V8ProfilerAgentImpl::V8ProfilerAgentImpl(V8Debugger* debugger)
-    : m_debugger(static_cast<V8DebuggerImpl*>(debugger))
+V8ProfilerAgentImpl::V8ProfilerAgentImpl(V8InspectorSessionImpl* session)
+    : m_debugger(session->debugger())
     , m_isolate(m_debugger->isolate())
     , m_state(nullptr)
     , m_frontend(nullptr)
diff --git a/third_party/WebKit/Source/platform/v8_inspector/V8ProfilerAgentImpl.h b/third_party/WebKit/Source/platform/v8_inspector/V8ProfilerAgentImpl.h
index c085759..4766a9d5 100644
--- a/third_party/WebKit/Source/platform/v8_inspector/V8ProfilerAgentImpl.h
+++ b/third_party/WebKit/Source/platform/v8_inspector/V8ProfilerAgentImpl.h
@@ -17,11 +17,12 @@
 namespace blink {
 
 class V8DebuggerImpl;
+class V8InspectorSessionImpl;
 
 class V8ProfilerAgentImpl : public V8ProfilerAgent {
     PROTOCOL_DISALLOW_COPY(V8ProfilerAgentImpl);
 public:
-    explicit V8ProfilerAgentImpl(V8Debugger*);
+    explicit V8ProfilerAgentImpl(V8InspectorSessionImpl*);
     ~V8ProfilerAgentImpl() override;
 
     void setInspectorState(protocol::DictionaryValue* state) override { m_state = state; }
diff --git a/third_party/WebKit/Source/platform/v8_inspector/V8RuntimeAgentImpl.cpp b/third_party/WebKit/Source/platform/v8_inspector/V8RuntimeAgentImpl.cpp
index bbb1298..179e080 100644
--- a/third_party/WebKit/Source/platform/v8_inspector/V8RuntimeAgentImpl.cpp
+++ b/third_party/WebKit/Source/platform/v8_inspector/V8RuntimeAgentImpl.cpp
@@ -37,7 +37,7 @@
 #include "platform/v8_inspector/MuteConsoleScope.h"
 #include "platform/v8_inspector/RemoteObjectId.h"
 #include "platform/v8_inspector/V8DebuggerImpl.h"
-#include "platform/v8_inspector/V8InspectorConnectionImpl.h"
+#include "platform/v8_inspector/V8InspectorSessionImpl.h"
 #include "platform/v8_inspector/V8StringUtil.h"
 #include "platform/v8_inspector/public/V8DebuggerClient.h"
 
@@ -57,24 +57,17 @@
     return hasError;
 }
 
-PassOwnPtr<V8RuntimeAgent> V8RuntimeAgent::create(V8Debugger* debugger, int contextGroupId)
-{
-    return adoptPtr(new V8RuntimeAgentImpl(static_cast<V8DebuggerImpl*>(debugger), contextGroupId));
-}
-
-V8RuntimeAgentImpl::V8RuntimeAgentImpl(V8DebuggerImpl* debugger, int contextGroupId)
-    : m_connection(V8InspectorConnectionImpl::create(debugger, contextGroupId))
+V8RuntimeAgentImpl::V8RuntimeAgentImpl(V8InspectorSessionImpl* session)
+    : m_session(session)
     , m_state(nullptr)
     , m_frontend(nullptr)
-    , m_debugger(debugger)
+    , m_debugger(session->debugger())
     , m_enabled(false)
 {
-    m_debugger->addRuntimeAgent(m_connection->contextGroupId(), this);
 }
 
 V8RuntimeAgentImpl::~V8RuntimeAgentImpl()
 {
-    m_debugger->removeRuntimeAgent(m_connection->contextGroupId());
 }
 
 void V8RuntimeAgentImpl::evaluate(
@@ -96,7 +89,7 @@
         contextId = executionContextId.fromJust();
     } else {
         InspectedContext* mainInGroup = nullptr;
-        if (const V8DebuggerImpl::ContextByIdMap* contexts = m_debugger->contextGroup(m_connection->contextGroupId())) {
+        if (const V8DebuggerImpl::ContextByIdMap* contexts = m_debugger->contextGroup(m_session->contextGroupId())) {
             for (auto& idContext : *contexts) {
                 if (idContext.second->isMainInGroup()) {
                     mainInGroup = idContext.second;
@@ -111,7 +104,7 @@
         contextId = mainInGroup->contextId();
     }
 
-    InjectedScript* injectedScript = m_connection->findInjectedScript(errorString, contextId);
+    InjectedScript* injectedScript = m_session->findInjectedScript(errorString, contextId);
     if (!injectedScript)
         return;
 
@@ -134,7 +127,7 @@
 
     v8::MaybeLocal<v8::Value> maybeResultValue = m_debugger->compileAndRunInternalScript(injectedScript->context()->context(), toV8String(injectedScript->isolate(), expression));
     // InjectedScript may be gone after any evaluate call - find it again.
-    injectedScript = m_connection->findInjectedScript(errorString, contextId);
+    injectedScript = m_session->findInjectedScript(errorString, contextId);
     if (!injectedScript)
         return;
 
@@ -163,7 +156,7 @@
     OwnPtr<RemoteObjectId> remoteId = RemoteObjectId::parse(errorString, objectId);
     if (!remoteId)
         return;
-    InjectedScript* injectedScript = m_connection->findInjectedScript(errorString, remoteId.get());
+    InjectedScript* injectedScript = m_session->findInjectedScript(errorString, remoteId.get());
     if (!injectedScript)
         return;
 
@@ -200,7 +193,7 @@
 
     v8::MaybeLocal<v8::Value> maybeFunctionValue = m_debugger->compileAndRunInternalScript(injectedScript->context()->context(), toV8String(injectedScript->isolate(), "(" + expression + ")"));
     // InjectedScript may be gone after any evaluate call - find it again.
-    injectedScript = m_connection->findInjectedScript(errorString, remoteId.get());
+    injectedScript = m_session->findInjectedScript(errorString, remoteId.get());
     if (!injectedScript)
         return;
 
@@ -222,7 +215,7 @@
 
     v8::MaybeLocal<v8::Value> maybeResultValue = m_debugger->callFunction(functionValue.As<v8::Function>(), injectedScript->context()->context(), object, argc, argv.get());
     // InjectedScript may be gone after any evaluate call - find it again.
-    injectedScript = m_connection->findInjectedScript(errorString, remoteId.get());
+    injectedScript = m_session->findInjectedScript(errorString, remoteId.get());
     if (!injectedScript)
         return;
 
@@ -244,7 +237,7 @@
     OwnPtr<RemoteObjectId> remoteId = RemoteObjectId::parse(errorString, objectId);
     if (!remoteId)
         return;
-    InjectedScript* injectedScript = m_connection->findInjectedScript(errorString, remoteId.get());
+    InjectedScript* injectedScript = m_session->findInjectedScript(errorString, remoteId.get());
     if (!injectedScript)
         return;
 
@@ -295,7 +288,7 @@
     OwnPtr<RemoteObjectId> remoteId = RemoteObjectId::parse(errorString, objectId);
     if (!remoteId)
         return;
-    InjectedScript* injectedScript = m_connection->findInjectedScript(errorString, remoteId.get());
+    InjectedScript* injectedScript = m_session->findInjectedScript(errorString, remoteId.get());
     if (!injectedScript)
         return;
     bool pausingOnNextStatement = m_debugger->pausingOnNextStatement();
@@ -311,7 +304,7 @@
     bool pausingOnNextStatement = m_debugger->pausingOnNextStatement();
     if (pausingOnNextStatement)
         m_debugger->setPauseOnNextStatement(false);
-    m_connection->releaseObjectGroup(objectGroup);
+    m_session->releaseObjectGroup(objectGroup);
     if (pausingOnNextStatement)
         m_debugger->setPauseOnNextStatement(true);
 }
@@ -324,7 +317,7 @@
 void V8RuntimeAgentImpl::setCustomObjectFormatterEnabled(ErrorString*, bool enabled)
 {
     m_state->setBoolean(V8RuntimeAgentImplState::customObjectFormatterEnabled, enabled);
-    m_connection->setCustomObjectFormatterEnabled(enabled);
+    m_session->setCustomObjectFormatterEnabled(enabled);
 }
 
 void V8RuntimeAgentImpl::compileScript(ErrorString* errorString,
@@ -339,7 +332,7 @@
         *errorString = "Runtime agent is not enabled";
         return;
     }
-    InjectedScript* injectedScript = m_connection->findInjectedScript(errorString, executionContextId);
+    InjectedScript* injectedScript = m_session->findInjectedScript(errorString, executionContextId);
     if (!injectedScript)
         return;
 
@@ -380,7 +373,7 @@
         *errorString = "Runtime agent is not enabled";
         return;
     }
-    InjectedScript* injectedScript = m_connection->findInjectedScript(errorString, executionContextId);
+    InjectedScript* injectedScript = m_session->findInjectedScript(errorString, executionContextId);
     if (!injectedScript)
         return;
 
@@ -414,7 +407,7 @@
     v8::MaybeLocal<v8::Value> maybeResultValue = m_debugger->runCompiledScript(context, script);
 
     // InjectedScript may be gone after any evaluate call - find it again.
-    injectedScript = m_connection->findInjectedScript(errorString, executionContextId);
+    injectedScript = m_session->findInjectedScript(errorString, executionContextId);
     if (!injectedScript)
         return;
 
@@ -445,14 +438,14 @@
     ErrorString error;
     enable(&error);
     if (m_state->booleanProperty(V8RuntimeAgentImplState::customObjectFormatterEnabled, false))
-        m_connection->setCustomObjectFormatterEnabled(true);
+        m_session->setCustomObjectFormatterEnabled(true);
 }
 
 void V8RuntimeAgentImpl::enable(ErrorString* errorString)
 {
     m_enabled = true;
     v8::HandleScope handles(m_debugger->isolate());
-    m_connection->reportAllContexts(this);
+    m_session->reportAllContexts(this);
 }
 
 void V8RuntimeAgentImpl::disable(ErrorString* errorString)
@@ -460,23 +453,24 @@
     if (!m_enabled)
         return;
     m_enabled = false;
+    m_session->discardInjectedScripts();
     reset();
 }
 
 void V8RuntimeAgentImpl::setClearConsoleCallback(PassOwnPtr<V8RuntimeAgent::ClearConsoleCallback> callback)
 {
-    m_connection->setClearConsoleCallback(callback);
+    m_session->setClearConsoleCallback(callback);
 }
 
 void V8RuntimeAgentImpl::setInspectObjectCallback(PassOwnPtr<V8RuntimeAgent::InspectCallback> callback)
 {
-    m_connection->setInspectObjectCallback(callback);
+    m_session->setInspectObjectCallback(callback);
 }
 
 PassOwnPtr<RemoteObject> V8RuntimeAgentImpl::wrapObject(v8::Local<v8::Context> context, v8::Local<v8::Value> value, const String16& groupName, bool generatePreview)
 {
     ErrorString errorString;
-    InjectedScript* injectedScript = m_connection->findInjectedScript(&errorString, V8Debugger::contextId(context));
+    InjectedScript* injectedScript = m_session->findInjectedScript(&errorString, V8Debugger::contextId(context));
     if (!injectedScript)
         return nullptr;
     return injectedScript->wrapObject(&errorString, value, groupName, false, generatePreview);
@@ -485,7 +479,7 @@
 PassOwnPtr<RemoteObject> V8RuntimeAgentImpl::wrapTable(v8::Local<v8::Context> context, v8::Local<v8::Value> table, v8::Local<v8::Value> columns)
 {
     ErrorString errorString;
-    InjectedScript* injectedScript = m_connection->findInjectedScript(&errorString, V8Debugger::contextId(context));
+    InjectedScript* injectedScript = m_session->findInjectedScript(&errorString, V8Debugger::contextId(context));
     if (!injectedScript)
         return nullptr;
     return injectedScript->wrapTable(table, columns);
@@ -493,7 +487,7 @@
 
 void V8RuntimeAgentImpl::disposeObjectGroup(const String16& groupName)
 {
-    m_connection->releaseObjectGroup(groupName);
+    m_session->releaseObjectGroup(groupName);
 }
 
 v8::Local<v8::Value> V8RuntimeAgentImpl::findObject(ErrorString* errorString, const String16& objectId, v8::Local<v8::Context>* context, String16* groupName)
@@ -501,7 +495,7 @@
     OwnPtr<RemoteObjectId> remoteId = RemoteObjectId::parse(errorString, objectId);
     if (!remoteId)
         return v8::Local<v8::Value>();
-    InjectedScript* injectedScript = m_connection->findInjectedScript(errorString, remoteId.get());
+    InjectedScript* injectedScript = m_session->findInjectedScript(errorString, remoteId.get());
     if (!injectedScript)
         return v8::Local<v8::Value>();
     v8::Local<v8::Value> objectValue;
@@ -517,15 +511,14 @@
 
 void V8RuntimeAgentImpl::addInspectedObject(PassOwnPtr<Inspectable> inspectable)
 {
-    m_connection->addInspectedObject(inspectable);
+    m_session->addInspectedObject(inspectable);
 }
 
 void V8RuntimeAgentImpl::reset()
 {
     m_compiledScripts.clear();
-    m_connection->resetInjectedScripts();
     if (m_enabled) {
-        if (const V8DebuggerImpl::ContextByIdMap* contexts = m_debugger->contextGroup(m_connection->contextGroupId())) {
+        if (const V8DebuggerImpl::ContextByIdMap* contexts = m_debugger->contextGroup(m_session->contextGroupId())) {
             for (auto& idContext : *contexts)
                 idContext.second->setReported(false);
         }
diff --git a/third_party/WebKit/Source/platform/v8_inspector/V8RuntimeAgentImpl.h b/third_party/WebKit/Source/platform/v8_inspector/V8RuntimeAgentImpl.h
index 37605384..935af12b 100644
--- a/third_party/WebKit/Source/platform/v8_inspector/V8RuntimeAgentImpl.h
+++ b/third_party/WebKit/Source/platform/v8_inspector/V8RuntimeAgentImpl.h
@@ -41,7 +41,7 @@
 class InspectedContext;
 class RemoteObjectIdBase;
 class V8DebuggerImpl;
-class V8InspectorConnectionImpl;
+class V8InspectorSessionImpl;
 
 namespace protocol {
 class DictionaryValue;
@@ -52,7 +52,7 @@
 class V8RuntimeAgentImpl : public V8RuntimeAgent {
     PROTOCOL_DISALLOW_COPY(V8RuntimeAgentImpl);
 public:
-    V8RuntimeAgentImpl(V8DebuggerImpl*, int contextGroupId);
+    explicit V8RuntimeAgentImpl(V8InspectorSessionImpl*);
     ~V8RuntimeAgentImpl() override;
 
     // State management methods.
@@ -114,9 +114,6 @@
         OwnPtr<protocol::Runtime::RemoteObject>* result,
         Maybe<protocol::Runtime::ExceptionDetails>*) override;
 
-    V8DebuggerImpl* debugger() { return m_debugger; }
-    V8InspectorConnectionImpl* connection() { return m_connection.get(); }
-
     void reset();
     void reportExecutionContextCreated(InspectedContext*);
     void reportExecutionContextDestroyed(InspectedContext*);
@@ -130,8 +127,7 @@
     void addInspectedObject(PassOwnPtr<Inspectable>) override;
 
 private:
-    // TODO(dgozman): reverse ownership.
-    OwnPtr<V8InspectorConnectionImpl> m_connection;
+    V8InspectorSessionImpl* m_session;
     protocol::DictionaryValue* m_state;
     protocol::Frontend::Runtime* m_frontend;
     V8DebuggerImpl* m_debugger;
diff --git a/third_party/WebKit/Source/platform/v8_inspector/public/V8Debugger.h b/third_party/WebKit/Source/platform/v8_inspector/public/V8Debugger.h
index 217426d0..b2238bc 100644
--- a/third_party/WebKit/Source/platform/v8_inspector/public/V8Debugger.h
+++ b/third_party/WebKit/Source/platform/v8_inspector/public/V8Debugger.h
@@ -15,6 +15,7 @@
 
 class V8ContextInfo;
 class V8DebuggerClient;
+class V8InspectorSession;
 class V8StackTrace;
 
 namespace protocol {
@@ -43,6 +44,8 @@
     // TODO(dgozman): remove this one.
     virtual void resetContextGroup(int contextGroupId) = 0;
 
+    virtual PassOwnPtr<V8InspectorSession> connect(int contextGroupId) = 0;
+
     static v8::Local<v8::Symbol> scopeExtensionSymbol(v8::Isolate*);
     static bool isCommandLineAPIMethod(const String16& name);
     static bool isCommandLineAPIGetter(const String16& name);
diff --git a/third_party/WebKit/Source/platform/v8_inspector/public/V8DebuggerAgent.h b/third_party/WebKit/Source/platform/v8_inspector/public/V8DebuggerAgent.h
index 81613f5..b182130 100644
--- a/third_party/WebKit/Source/platform/v8_inspector/public/V8DebuggerAgent.h
+++ b/third_party/WebKit/Source/platform/v8_inspector/public/V8DebuggerAgent.h
@@ -17,7 +17,6 @@
 public:
     static const char backtraceObjectGroup[];
 
-    static PassOwnPtr<V8DebuggerAgent> create(V8RuntimeAgent*);
     virtual ~V8DebuggerAgent() { }
 
     // API for the embedder to report native activities.
diff --git a/third_party/WebKit/Source/platform/v8_inspector/public/V8HeapProfilerAgent.h b/third_party/WebKit/Source/platform/v8_inspector/public/V8HeapProfilerAgent.h
index 30f8eee..523e048 100644
--- a/third_party/WebKit/Source/platform/v8_inspector/public/V8HeapProfilerAgent.h
+++ b/third_party/WebKit/Source/platform/v8_inspector/public/V8HeapProfilerAgent.h
@@ -15,7 +15,6 @@
 
 class PLATFORM_EXPORT V8HeapProfilerAgent : public protocol::Backend::HeapProfiler, public V8Debugger::Agent<protocol::Frontend::HeapProfiler> {
 public:
-    static PassOwnPtr<V8HeapProfilerAgent> create(v8::Isolate*, V8RuntimeAgent*);
     virtual ~V8HeapProfilerAgent() { }
 
     virtual void requestHeapStatsUpdate() = 0;
diff --git a/third_party/WebKit/Source/platform/v8_inspector/public/V8InspectorSession.h b/third_party/WebKit/Source/platform/v8_inspector/public/V8InspectorSession.h
new file mode 100644
index 0000000..d8befe1
--- /dev/null
+++ b/third_party/WebKit/Source/platform/v8_inspector/public/V8InspectorSession.h
@@ -0,0 +1,30 @@
+// Copyright 2016 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 V8InspectorSession_h
+#define V8InspectorSession_h
+
+#include "platform/PlatformExport.h"
+#include "wtf/PassOwnPtr.h"
+
+namespace blink {
+
+class V8DebuggerAgent;
+class V8HeapProfilerAgent;
+class V8ProfilerAgent;
+class V8RuntimeAgent;
+
+class PLATFORM_EXPORT V8InspectorSession {
+public:
+    virtual ~V8InspectorSession() { }
+
+    virtual V8DebuggerAgent* debuggerAgent() = 0;
+    virtual V8HeapProfilerAgent* heapProfilerAgent() = 0;
+    virtual V8ProfilerAgent* profilerAgent() = 0;
+    virtual V8RuntimeAgent* runtimeAgent() = 0;
+};
+
+} // namespace blink
+
+#endif // V8InspectorSession_h
diff --git a/third_party/WebKit/Source/platform/v8_inspector/public/V8ProfilerAgent.h b/third_party/WebKit/Source/platform/v8_inspector/public/V8ProfilerAgent.h
index 0e4613b..24bef95 100644
--- a/third_party/WebKit/Source/platform/v8_inspector/public/V8ProfilerAgent.h
+++ b/third_party/WebKit/Source/platform/v8_inspector/public/V8ProfilerAgent.h
@@ -13,7 +13,6 @@
 
 class PLATFORM_EXPORT V8ProfilerAgent : public protocol::Backend::Profiler, public V8Debugger::Agent<protocol::Frontend::Profiler> {
 public:
-    static PassOwnPtr<V8ProfilerAgent> create(V8Debugger*);
     virtual ~V8ProfilerAgent() { }
 
     // API for the embedder.
diff --git a/third_party/WebKit/Source/platform/v8_inspector/public/V8RuntimeAgent.h b/third_party/WebKit/Source/platform/v8_inspector/public/V8RuntimeAgent.h
index 6d2c58c8..4beef808 100644
--- a/third_party/WebKit/Source/platform/v8_inspector/public/V8RuntimeAgent.h
+++ b/third_party/WebKit/Source/platform/v8_inspector/public/V8RuntimeAgent.h
@@ -26,7 +26,6 @@
         virtual ~Inspectable() { }
     };
 
-    static PassOwnPtr<V8RuntimeAgent> create(V8Debugger*, int contextGroupId);
     virtual ~V8RuntimeAgent() { }
 
     // Embedder API.
diff --git a/third_party/WebKit/Source/platform/web_process_memory_dump_impl.cc b/third_party/WebKit/Source/platform/web_process_memory_dump_impl.cc
index 2e1745b..3c2c2c8 100644
--- a/third_party/WebKit/Source/platform/web_process_memory_dump_impl.cc
+++ b/third_party/WebKit/Source/platform/web_process_memory_dump_impl.cc
@@ -4,9 +4,8 @@
 
 #include "platform/web_process_memory_dump_impl.h"
 
-#include <stddef.h>
-
 #include "base/memory/discardable_memory.h"
+#include "base/memory/ptr_util.h"
 #include "base/strings/stringprintf.h"
 #include "base/trace_event/heap_profiler_heap_dump_writer.h"
 #include "base/trace_event/process_memory_dump.h"
@@ -15,6 +14,8 @@
 #include "platform/web_memory_allocator_dump_impl.h"
 #include "skia/ext/skia_trace_memory_dump_impl.h"
 
+#include <stddef.h>
+
 namespace blink {
 
 WebProcessMemoryDumpImpl::WebProcessMemoryDumpImpl()
@@ -150,7 +151,7 @@
 
 SkTraceMemoryDump* WebProcessMemoryDumpImpl::createDumpAdapterForSkia(
     const blink::WebString& dump_name_prefix) {
-  sk_trace_dump_list_.push_back(make_scoped_ptr(
+  sk_trace_dump_list_.push_back(base::WrapUnique(
       new skia::SkiaTraceMemoryDumpImpl(
           dump_name_prefix.utf8(), level_of_detail_, process_memory_dump_)));
   return sk_trace_dump_list_.back().get();
@@ -174,7 +175,7 @@
   if (!bytes_by_context.empty()) {
     scoped_refptr<base::trace_event::MemoryDumpSessionState> session_state =
         process_memory_dump_->session_state();
-    scoped_ptr<base::trace_event::TracedValue> heap_dump = ExportHeapDump(
+    std::unique_ptr<base::trace_event::TracedValue> heap_dump = ExportHeapDump(
         bytes_by_context, session_state->stack_frame_deduplicator(),
         session_state->type_name_deduplicator());
     process_memory_dump_->AddHeapDump(allocator_name, std::move(heap_dump));
diff --git a/third_party/WebKit/Source/platform/web_process_memory_dump_impl.h b/third_party/WebKit/Source/platform/web_process_memory_dump_impl.h
index 9f16b5a..e1ee7bf 100644
--- a/third_party/WebKit/Source/platform/web_process_memory_dump_impl.h
+++ b/third_party/WebKit/Source/platform/web_process_memory_dump_impl.h
@@ -7,13 +7,13 @@
 
 #include "base/gtest_prod_util.h"
 #include "base/macros.h"
-#include "base/memory/scoped_ptr.h"
 #include "base/trace_event/memory_dump_request_args.h"
 #include "public/platform/WebProcessMemoryDump.h"
 #include "wtf/HashMap.h"
 #include "wtf/OwnPtr.h"
 
 #include <map>
+#include <memory>
 #include <vector>
 
 namespace base {
@@ -90,7 +90,7 @@
       base::trace_event::MemoryAllocatorDump* memory_allocator_dump);
 
   // Only for the case of ProcessMemoryDump being owned (i.e. the default ctor).
-  scoped_ptr<base::trace_event::ProcessMemoryDump> owned_process_memory_dump_;
+  std::unique_ptr<base::trace_event::ProcessMemoryDump> owned_process_memory_dump_;
 
   // The underlying ProcessMemoryDump instance to which the
   // createMemoryAllocatorDump() calls will be proxied to.
@@ -108,7 +108,7 @@
           OwnPtr<WebMemoryAllocatorDumpImpl>> memory_allocator_dumps_;
 
   // Stores SkTraceMemoryDump for the current ProcessMemoryDump.
-  std::vector<scoped_ptr<skia::SkiaTraceMemoryDumpImpl>> sk_trace_dump_list_;
+  std::vector<std::unique_ptr<skia::SkiaTraceMemoryDumpImpl>> sk_trace_dump_list_;
 
   DISALLOW_COPY_AND_ASSIGN(WebProcessMemoryDumpImpl);
 };
diff --git a/third_party/WebKit/Source/platform/web_process_memory_dump_impl_test.cc b/third_party/WebKit/Source/platform/web_process_memory_dump_impl_test.cc
index 8d4ad74..dd68132e 100644
--- a/third_party/WebKit/Source/platform/web_process_memory_dump_impl_test.cc
+++ b/third_party/WebKit/Source/platform/web_process_memory_dump_impl_test.cc
@@ -20,16 +20,16 @@
 // behaves correctly, performs the right transfers of memory ownerships and
 // doesn't leak objects.
 TEST(WebProcessMemoryDumpImplTest, IntegrationTest) {
-  scoped_ptr<base::trace_event::TracedValue> traced_value(
+  std::unique_ptr<base::trace_event::TracedValue> traced_value(
           new base::trace_event::TracedValue());
 
-  scoped_ptr<WebProcessMemoryDumpImpl> wpmd1(new WebProcessMemoryDumpImpl());
+  std::unique_ptr<WebProcessMemoryDumpImpl> wpmd1(new WebProcessMemoryDumpImpl());
   auto wmad1 = wpmd1->createMemoryAllocatorDump("1/1");
   auto wmad2 = wpmd1->createMemoryAllocatorDump("1/2");
   ASSERT_EQ(wmad1, wpmd1->getMemoryAllocatorDump("1/1"));
   ASSERT_EQ(wmad2, wpmd1->getMemoryAllocatorDump("1/2"));
 
-  scoped_ptr<WebProcessMemoryDumpImpl> wpmd2(new WebProcessMemoryDumpImpl());
+  std::unique_ptr<WebProcessMemoryDumpImpl> wpmd2(new WebProcessMemoryDumpImpl());
   wpmd2->createMemoryAllocatorDump("2/1");
   wpmd2->createMemoryAllocatorDump("2/2");
 
diff --git a/third_party/WebKit/Source/web/ChromeClientImpl.cpp b/third_party/WebKit/Source/web/ChromeClientImpl.cpp
index 2de9423..504e3eb 100644
--- a/third_party/WebKit/Source/web/ChromeClientImpl.cpp
+++ b/third_party/WebKit/Source/web/ChromeClientImpl.cpp
@@ -657,19 +657,19 @@
         m_webView->client()->printPage(WebLocalFrameImpl::fromFrame(frame));
 }
 
-RawPtr<ColorChooser> ChromeClientImpl::openColorChooser(LocalFrame* frame, ColorChooserClient* chooserClient, const Color&)
+ColorChooser* ChromeClientImpl::openColorChooser(LocalFrame* frame, ColorChooserClient* chooserClient, const Color&)
 {
     notifyPopupOpeningObservers();
-    RawPtr<ColorChooserUIController> controller = nullptr;
+    ColorChooserUIController* controller = nullptr;
     if (RuntimeEnabledFeatures::pagePopupEnabled())
         controller = ColorChooserPopupUIController::create(frame, this, chooserClient);
     else
         controller = ColorChooserUIController::create(frame, chooserClient);
     controller->openUI();
-    return controller.release();
+    return controller;
 }
 
-RawPtr<DateTimeChooser> ChromeClientImpl::openDateTimeChooser(DateTimeChooserClient* pickerClient, const DateTimeChooserParameters& parameters)
+DateTimeChooser* ChromeClientImpl::openDateTimeChooser(DateTimeChooserClient* pickerClient, const DateTimeChooserParameters& parameters)
 {
     notifyPopupOpeningObservers();
 #if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
@@ -876,7 +876,7 @@
     return m_webView->hasOpenedPopup();
 }
 
-RawPtr<PopupMenu> ChromeClientImpl::openPopupMenu(LocalFrame& frame, HTMLSelectElement& select)
+PopupMenu* ChromeClientImpl::openPopupMenu(LocalFrame& frame, HTMLSelectElement& select)
 {
     notifyPopupOpeningObservers();
     if (WebViewImpl::useExternalPopupMenus())
diff --git a/third_party/WebKit/Source/web/ChromeClientImpl.h b/third_party/WebKit/Source/web/ChromeClientImpl.h
index c1f32b34..b180e74 100644
--- a/third_party/WebKit/Source/web/ChromeClientImpl.h
+++ b/third_party/WebKit/Source/web/ChromeClientImpl.h
@@ -106,8 +106,8 @@
     void dispatchViewportPropertiesDidChange(const ViewportDescription&) const override;
     void printDelegate(LocalFrame*) override;
     void annotatedRegionsChanged() override;
-    RawPtr<ColorChooser> openColorChooser(LocalFrame*, ColorChooserClient*, const Color&) override;
-    RawPtr<DateTimeChooser> openDateTimeChooser(DateTimeChooserClient*, const DateTimeChooserParameters&) override;
+    ColorChooser* openColorChooser(LocalFrame*, ColorChooserClient*, const Color&) override;
+    DateTimeChooser* openDateTimeChooser(DateTimeChooserClient*, const DateTimeChooserParameters&) override;
     void openFileChooser(LocalFrame*, PassRefPtr<FileChooser>) override;
     void enumerateChosenDirectory(FileChooser*) override;
     void setCursor(const Cursor&, LocalFrame* localRoot) override;
@@ -142,7 +142,7 @@
     void setCursorOverridden(bool);
 
     bool hasOpenedPopup() const override;
-    RawPtr<PopupMenu> openPopupMenu(LocalFrame&, HTMLSelectElement&) override;
+    PopupMenu* openPopupMenu(LocalFrame&, HTMLSelectElement&) override;
     PagePopup* openPagePopup(PagePopupClient*);
     void closePagePopup(PagePopup*);
     DOMWindow* pagePopupWindowForTesting() const override;
diff --git a/third_party/WebKit/Source/web/RotationViewportAnchor.cpp b/third_party/WebKit/Source/web/RotationViewportAnchor.cpp
index 8cf14252..bd94e0f 100644
--- a/third_party/WebKit/Source/web/RotationViewportAnchor.cpp
+++ b/third_party/WebKit/Source/web/RotationViewportAnchor.cpp
@@ -192,7 +192,7 @@
 
 FloatPoint RotationViewportAnchor::getInnerOrigin(const FloatSize& innerSize) const
 {
-    if (!m_anchorNode || !m_anchorNode->inDocument())
+    if (!m_anchorNode || !m_anchorNode->inShadowIncludingDocument())
         return m_visualViewportInDocument;
 
     const LayoutRect currentNodeBounds = m_anchorNode->boundingBox();
diff --git a/third_party/WebKit/Source/web/TextFinder.cpp b/third_party/WebKit/Source/web/TextFinder.cpp
index d1bb76c..a416d0a 100644
--- a/third_party/WebKit/Source/web/TextFinder.cpp
+++ b/third_party/WebKit/Source/web/TextFinder.cpp
@@ -500,7 +500,7 @@
 
     size_t deadMatches = 0;
     for (FindMatch& match : m_findMatchesCache) {
-        if (!match.m_range->boundaryPointsValid() || !match.m_range->startContainer()->inDocument())
+        if (!match.m_range->boundaryPointsValid() || !match.m_range->startContainer()->inShadowIncludingDocument())
             match.m_rect = FloatRect();
         else if (!m_findMatchRectsAreValid)
             match.m_rect = findInPageRectFromRange(match.m_range.get());
@@ -605,7 +605,7 @@
     ASSERT_WITH_SECURITY_IMPLICATION(index < m_findMatchesCache.size());
 
     RawPtr<Range> range = m_findMatchesCache[index].m_range;
-    if (!range->boundaryPointsValid() || !range->startContainer()->inDocument())
+    if (!range->boundaryPointsValid() || !range->startContainer()->inShadowIncludingDocument())
         return -1;
 
     // Check if the match is already selected.
diff --git a/third_party/WebKit/Source/web/WebDevToolsAgentImpl.cpp b/third_party/WebKit/Source/web/WebDevToolsAgentImpl.cpp
index 032e1471..aa6b0d6b 100644
--- a/third_party/WebKit/Source/web/WebDevToolsAgentImpl.cpp
+++ b/third_party/WebKit/Source/web/WebDevToolsAgentImpl.cpp
@@ -78,6 +78,8 @@
 #include "platform/inspector_protocol/Dispatcher.h"
 #include "platform/inspector_protocol/Frontend.h"
 #include "platform/inspector_protocol/Values.h"
+#include "platform/v8_inspector/public/V8Debugger.h"
+#include "platform/v8_inspector/public/V8InspectorSession.h"
 #include "public/platform/Platform.h"
 #include "public/platform/WebLayerTreeView.h"
 #include "public/platform/WebRect.h"
@@ -378,6 +380,7 @@
     m_resourceContentLoader->dispose();
     m_agents.discardAgents();
     m_instrumentingAgents->reset();
+    m_v8Session.clear();
 }
 
 void WebDevToolsAgentImpl::initializeDeferredAgents()
@@ -390,13 +393,14 @@
     MainThreadDebugger* mainThreadDebugger = MainThreadDebugger::instance();
     v8::Isolate* isolate = V8PerIsolateData::mainThreadIsolate();
 
+    m_v8Session = mainThreadDebugger->debugger()->connect(mainThreadDebugger->contextGroupId(m_inspectedFrames->root()));
+    V8RuntimeAgent* runtimeAgent = m_v8Session->runtimeAgent();
+
     RawPtr<InspectorInspectorAgent> inspectorAgent = InspectorInspectorAgent::create();
     InspectorInspectorAgent* inspectorAgentPtr = inspectorAgent.get();
     m_agents.append(inspectorAgent.release());
 
-    RawPtr<PageRuntimeAgent> pageRuntimeAgent = PageRuntimeAgent::create(this, mainThreadDebugger->debugger(), m_inspectedFrames.get(), mainThreadDebugger->contextGroupId(m_inspectedFrames->root()));
-    V8RuntimeAgent* runtimeAgent = pageRuntimeAgent->v8Agent();
-    m_agents.append(pageRuntimeAgent.release());
+    m_agents.append(PageRuntimeAgent::create(this, runtimeAgent, m_inspectedFrames.get()));
 
     RawPtr<InspectorDOMAgent> domAgent = InspectorDOMAgent::create(isolate, m_inspectedFrames.get(), runtimeAgent, m_overlay.get());
     m_domAgent = domAgent.get();
@@ -422,11 +426,11 @@
 
     m_agents.append(InspectorIndexedDBAgent::create(m_inspectedFrames.get()));
 
-    RawPtr<InspectorDebuggerAgent> debuggerAgent = PageDebuggerAgent::create(m_inspectedFrames.get(), runtimeAgent);
+    RawPtr<InspectorDebuggerAgent> debuggerAgent = PageDebuggerAgent::create(m_v8Session->debuggerAgent(), m_inspectedFrames.get());
     InspectorDebuggerAgent* debuggerAgentPtr = debuggerAgent.get();
     m_agents.append(debuggerAgent.release());
 
-    RawPtr<PageConsoleAgent> pageConsoleAgent = PageConsoleAgent::create(runtimeAgent, debuggerAgentPtr->v8Agent(), m_domAgent, m_inspectedFrames.get());
+    RawPtr<PageConsoleAgent> pageConsoleAgent = PageConsoleAgent::create(runtimeAgent, m_v8Session->debuggerAgent(), m_domAgent, m_inspectedFrames.get());
     PageConsoleAgent* pageConsoleAgentPtr = pageConsoleAgent.get();
     m_agents.append(pageConsoleAgent.release());
 
@@ -442,9 +446,9 @@
 
     m_agents.append(InspectorInputAgent::create(m_inspectedFrames.get()));
 
-    m_agents.append(InspectorProfilerAgent::create(MainThreadDebugger::instance()->debugger(), m_overlay.get()));
+    m_agents.append(InspectorProfilerAgent::create(m_v8Session->profilerAgent(), m_overlay.get()));
 
-    m_agents.append(InspectorHeapProfilerAgent::create(isolate, runtimeAgent));
+    m_agents.append(InspectorHeapProfilerAgent::create(isolate, m_v8Session->heapProfilerAgent()));
 
     RawPtr<InspectorPageAgent> pageAgent = InspectorPageAgent::create(m_inspectedFrames.get(), this, m_resourceContentLoader.get(), debuggerAgentPtr);
     m_pageAgent = pageAgent.get();
diff --git a/third_party/WebKit/Source/web/WebDevToolsAgentImpl.h b/third_party/WebKit/Source/web/WebDevToolsAgentImpl.h
index a019547..2110ef0 100644
--- a/third_party/WebKit/Source/web/WebDevToolsAgentImpl.h
+++ b/third_party/WebKit/Source/web/WebDevToolsAgentImpl.h
@@ -56,6 +56,7 @@
 class PlatformKeyboardEvent;
 class PlatformMouseEvent;
 class PlatformTouchEvent;
+class V8InspectorSession;
 class WebDevToolsAgentClient;
 class WebFrameWidgetImpl;
 class WebInputEvent;
@@ -151,6 +152,7 @@
     Member<InspectorResourceContentLoader> m_resourceContentLoader;
     Member<InspectorOverlay> m_overlay;
     Member<InspectedFrames> m_inspectedFrames;
+    OwnPtr<V8InspectorSession> m_v8Session;
 
     Member<InspectorDOMAgent> m_domAgent;
     Member<InspectorPageAgent> m_pageAgent;
diff --git a/third_party/WebKit/Source/web/WebSettingsImpl.cpp b/third_party/WebKit/Source/web/WebSettingsImpl.cpp
index 0c0b2b9..d8dbe90 100644
--- a/third_party/WebKit/Source/web/WebSettingsImpl.cpp
+++ b/third_party/WebKit/Source/web/WebSettingsImpl.cpp
@@ -73,11 +73,6 @@
         m_settings->notifyGenericFontFamilyChange();
 }
 
-void WebSettingsImpl::setReportWheelOverscroll(bool enabled)
-{
-    m_settings->setReportWheelOverscroll(enabled);
-}
-
 void WebSettingsImpl::setForceZeroLayoutHeight(bool enabled)
 {
     m_settings->setForceZeroLayoutHeight(enabled);
diff --git a/third_party/WebKit/Source/web/WebSettingsImpl.h b/third_party/WebKit/Source/web/WebSettingsImpl.h
index a4e39a6..36d9a6e 100644
--- a/third_party/WebKit/Source/web/WebSettingsImpl.h
+++ b/third_party/WebKit/Source/web/WebSettingsImpl.h
@@ -97,7 +97,6 @@
     void setExperimentalWebGLEnabled(bool) override;
     void setFantasyFontFamily(const WebString&, UScriptCode = USCRIPT_COMMON) override;
     void setFixedFontFamily(const WebString&, UScriptCode = USCRIPT_COMMON) override;
-    void setReportWheelOverscroll(bool) override;
     void setForceZeroLayoutHeight(bool) override;
     void setFullscreenSupported(bool) override;
     void setHyperlinkAuditingEnabled(bool) override;
diff --git a/third_party/WebKit/Source/web/tests/WebFrameTest.cpp b/third_party/WebKit/Source/web/tests/WebFrameTest.cpp
index c261603..1187b648 100644
--- a/third_party/WebKit/Source/web/tests/WebFrameTest.cpp
+++ b/third_party/WebKit/Source/web/tests/WebFrameTest.cpp
@@ -8339,14 +8339,6 @@
     webViewHelper.initializeAndLoad(m_baseURL + "overscroll/overscroll.html", true, 0, &client, configureAndroid);
     webViewHelper.resize(WebSize(200, 200));
 
-    // On disabling ReportWheelOverscroll, overscroll is not reported on MouseWheel.
-    webViewHelper.webView()->settings()->setReportWheelOverscroll(false);
-    EXPECT_CALL(client, didOverscroll(_, _, _, _)).Times(0);
-    ScrollByWheel(&webViewHelper, 10, 10, 1000, 1000);
-    Mock::VerifyAndClearExpectations(&client);
-
-    // On enabling ReportWheelOverscroll, overscroll is reported on MouseWheel.
-    webViewHelper.webView()->settings()->setReportWheelOverscroll(true);
     EXPECT_CALL(client, didOverscroll(WebFloatSize(-1000, -1000), WebFloatSize(-1000, -1000), WebFloatPoint(), WebFloatSize()));
     ScrollByWheel(&webViewHelper, 10, 10, 1000, 1000);
     Mock::VerifyAndClearExpectations(&client);
diff --git a/third_party/WebKit/Source/wtf/LeakAnnotations.h b/third_party/WebKit/Source/wtf/LeakAnnotations.h
index 6697ee4d..34dba7a 100644
--- a/third_party/WebKit/Source/wtf/LeakAnnotations.h
+++ b/third_party/WebKit/Source/wtf/LeakAnnotations.h
@@ -131,7 +131,7 @@
 #define LEAK_SANITIZER_REGISTER_STATIC_LOCAL(Type, Object) WTF::RegisterStaticLocalReference<Type>::registerStatic(Object)
 #else
 #define WTF_INTERNAL_LEAK_SANITIZER_DISABLED_SCOPE
-#define LEAK_SANITIZER_IGNORE_OBJECT
+#define LEAK_SANITIZER_IGNORE_OBJECT(X) ((void)0)
 #define LEAK_SANITIZER_REGISTER_STATIC_LOCAL(Type, Object) Object
 #endif // USE(LEAK_SANITIZER)
 
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/controllers/manager.py b/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/controllers/manager.py
index d724353..b2fa663 100644
--- a/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/controllers/manager.py
+++ b/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/controllers/manager.py
@@ -84,8 +84,6 @@
         self.INSPECTOR_SUBDIR = 'inspector' + port.TEST_PATH_SEPARATOR
         self.PERF_SUBDIR = 'perf'
         self.WEBSOCKET_SUBDIR = 'websocket' + port.TEST_PATH_SEPARATOR
-        self.VIRTUAL_HTTP_SUBDIR = port.TEST_PATH_SEPARATOR.join([
-            'virtual', 'stable', 'http'])
         self.LAYOUT_TESTS_DIRECTORY = 'LayoutTests'
         self.ARCHIVED_RESULTS_LIMIT = 25
         self._http_server_started = False
@@ -225,7 +223,7 @@
         return (
             test.startswith(self.HTTP_SUBDIR) or
             self._is_websocket_test(test) or
-            self.VIRTUAL_HTTP_SUBDIR in test
+            self._port.TEST_PATH_SEPARATOR + self.HTTP_SUBDIR in test
         )
 
     def _is_inspector_test(self, test):
diff --git a/third_party/WebKit/public/BUILD.gn b/third_party/WebKit/public/BUILD.gn
index adcf3dd8..37bc00b 100644
--- a/third_party/WebKit/public/BUILD.gn
+++ b/third_party/WebKit/public/BUILD.gn
@@ -194,8 +194,16 @@
     "platform/modules/bluetooth/web_bluetooth.mojom",
     "platform/modules/geolocation/geolocation.mojom",
     "platform/modules/notifications/notification.mojom",
-    "platform/modules/payments/payment_request.mojom",
     "platform/modules/permissions/permission.mojom",
     "platform/modules/permissions/permission_status.mojom",
   ]
 }
+
+if (is_android) {
+  # GYP version: WebKit/public/blink.gyp:android_mojo_bindings_java
+  mojom("android_mojo_bindings") {
+    sources = [
+      "platform/modules/payments/payment_request.mojom",
+    ]
+  }
+}
diff --git a/third_party/WebKit/public/blink.gyp b/third_party/WebKit/public/blink.gyp
index 8a430d7f..72494d2 100644
--- a/third_party/WebKit/public/blink.gyp
+++ b/third_party/WebKit/public/blink.gyp
@@ -36,10 +36,12 @@
             'platform/modules/bluetooth/web_bluetooth.mojom',
             'platform/modules/geolocation/geolocation.mojom',
             'platform/modules/notifications/notification.mojom',
-            'platform/modules/payments/payment_request.mojom',
             'platform/modules/permissions/permission.mojom',
             'platform/modules/permissions/permission_status.mojom',
         ],
+        'blink_android_mojo_sources': [
+            'platform/modules/payments/payment_request.mojom',
+        ],
     },
     'targets': [
         {
@@ -98,7 +100,10 @@
             'target_name': 'mojo_bindings_blink_mojom',
             'type': 'none',
             'variables': {
-                'mojom_files': ['<@(blink_mojo_sources)'],
+                'mojom_files': [
+                    '<@(blink_mojo_sources)',
+                    '<@(blink_android_mojo_sources)',
+                ],
                 'mojom_variant': 'wtf',
                 'for_blink': 'true',
             },
@@ -127,4 +132,29 @@
             ],
         },
     ],
+    'conditions': [
+        ['OS == "android"', {
+            'targets': [
+                {
+                    'target_name': 'android_mojo_bindings_mojom',
+                    'type': 'none',
+                    'variables': {
+                        'mojom_files': ['<@(blink_android_mojo_sources)'],
+                    },
+                    'includes': [
+                        '../../../mojo/mojom_bindings_generator_explicit.gypi',
+                    ],
+                },
+                {
+                    # GN version: //third_party/WebKit/public:android_mojo_bindings_java
+                    'target_name': 'android_mojo_bindings_java',
+                    'type': 'static_library',
+                    'dependencies': [
+                        'android_mojo_bindings_mojom',
+                        '../../../mojo/mojo_public.gyp:mojo_bindings_java',
+                    ],
+                },
+            ],
+        }],
+    ],
 }
diff --git a/third_party/WebKit/public/platform/WebPassOwnPtr.h b/third_party/WebKit/public/platform/WebPassOwnPtr.h
index 9b2d34f..e818b70 100644
--- a/third_party/WebKit/public/platform/WebPassOwnPtr.h
+++ b/third_party/WebKit/public/platform/WebPassOwnPtr.h
@@ -7,11 +7,10 @@
 
 #include "public/platform/WebCommon.h"
 #include <cstddef>
+#include <memory>
 
 #if INSIDE_BLINK
 #include "wtf/PassOwnPtr.h"
-#else
-#include <base/memory/scoped_ptr.h>
 #endif
 
 namespace blink {
@@ -19,7 +18,7 @@
 // WebPassOwnPtr<T> is used to pass a T pointer with ownership from chromium
 // side to blink side. T's definition must be shared among all users
 // (especially between chromium and blink).
-// TODO(yhirano): Migrate to scoped_ptr or std::unique_ptr once the repository
+// TODO(yhirano): Migrate to std::unique_ptr once the repository
 // merge is done or C++11 std library is allowed.
 template <typename T>
 class WebPassOwnPtr final {
@@ -53,11 +52,11 @@
         return adoptPtr(ptr);
     }
 #else
-    operator scoped_ptr<T>()
+    operator std::unique_ptr<T>()
     {
         T* ptr = m_ptr;
         m_ptr = nullptr;
-        return scoped_ptr<T>(ptr);
+        return std::unique_ptr<T>(ptr);
     }
 #endif // INSIDE_BLINK
 
diff --git a/third_party/WebKit/public/platform/callback/DEPS b/third_party/WebKit/public/platform/callback/DEPS
index a8b8245..47e6224 100644
--- a/third_party/WebKit/public/platform/callback/DEPS
+++ b/third_party/WebKit/public/platform/callback/DEPS
@@ -7,5 +7,5 @@
     "+base/callback_helpers.h",
     "+base/logging.h",
     "+base/macros.h",
-    "+base/memory/scoped_ptr.h",
+    "+base/memory/ptr_util.h",
 ]
diff --git a/third_party/WebKit/public/platform/callback/WebClosure.h b/third_party/WebKit/public/platform/callback/WebClosure.h
index 8c0fe5c..5666e3f 100644
--- a/third_party/WebKit/public/platform/callback/WebClosure.h
+++ b/third_party/WebKit/public/platform/callback/WebClosure.h
@@ -9,9 +9,10 @@
 #include "base/callback.h"
 #include "base/callback_helpers.h"
 #include "base/macros.h"
-#include "base/memory/scoped_ptr.h"
+#include "base/memory/ptr_util.h"
 #include "public/platform/WebCommon.h"
 
+#include <memory>
 #include <utility>
 
 #if BLINK_IMPLEMENTATION
@@ -31,7 +32,7 @@
 
     explicit WebClosure(PassOwnPtr<SameThreadClosure> c)
     {
-        m_closure = base::Bind(&RunAndDelete, base::Passed(make_scoped_ptr(c.leakPtr())));
+        m_closure = base::Bind(&RunAndDelete, base::Passed(base::WrapUnique(c.leakPtr())));
     }
 #endif
 
@@ -62,7 +63,7 @@
 
 private:
 #if BLINK_IMPLEMENTATION
-    static void RunAndDelete(scoped_ptr<SameThreadClosure> c) { (*c)(); }
+    static void RunAndDelete(std::unique_ptr<SameThreadClosure> c) { (*c)(); }
 #endif
 
 #if DCHECK_IS_ON()
diff --git a/third_party/WebKit/public/platform/modules/bluetooth/web_bluetooth.mojom b/third_party/WebKit/public/platform/modules/bluetooth/web_bluetooth.mojom
index 66233dd..f70113e 100644
--- a/third_party/WebKit/public/platform/modules/bluetooth/web_bluetooth.mojom
+++ b/third_party/WebKit/public/platform/modules/bluetooth/web_bluetooth.mojom
@@ -61,7 +61,7 @@
   BLACKLISTED_WRITE,
   NOT_ALLOWED_TO_ACCESS_SERVICE,
   REQUEST_DEVICE_WITH_BLACKLISTED_UUID,
-  REQUEST_DEVICE_WITH_UNIQUE_ORIGIN,
+  REQUEST_DEVICE_FROM_CROSS_ORIGIN_IFRAME,
   REQUEST_DEVICE_WITHOUT_FRAME,
   // SyntaxError:
   // TODO(ortuno): Remove once we no longer use IPC.
diff --git a/third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerProvider.h b/third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerProvider.h
index e5fa982..0beb484c 100644
--- a/third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerProvider.h
+++ b/third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerProvider.h
@@ -56,7 +56,7 @@
     using WebServiceWorkerGetRegistrationCallbacks = WebCallbacks<WebPassOwnPtr<WebServiceWorkerRegistration::Handle>, const WebServiceWorkerError&>;
 
     // Each element's ownership is transferred.
-    // TODO(yhirano): Consider using vector<scoped_ptr<>>.
+    // TODO(yhirano): Consider using vector<std::unique_ptr<>>.
     using WebServiceWorkerGetRegistrationsCallbacks = WebCallbacks<WebPassOwnPtr<WebVector<WebServiceWorkerRegistration::Handle*>>, const WebServiceWorkerError&>;
     using WebServiceWorkerGetRegistrationForReadyCallbacks = WebCallbacks<WebPassOwnPtr<WebServiceWorkerRegistration::Handle>, void>;
 
diff --git a/third_party/WebKit/public/web/WebSettings.h b/third_party/WebKit/public/web/WebSettings.h
index e02a3316a..17cfafe 100644
--- a/third_party/WebKit/public/web/WebSettings.h
+++ b/third_party/WebKit/public/web/WebSettings.h
@@ -149,7 +149,6 @@
     virtual void setExperimentalWebGLEnabled(bool) = 0;
     virtual void setFantasyFontFamily(const WebString&, UScriptCode = USCRIPT_COMMON) = 0;
     virtual void setFixedFontFamily(const WebString&, UScriptCode = USCRIPT_COMMON) = 0;
-    virtual void setReportWheelOverscroll(bool) = 0;
     virtual void setForceZeroLayoutHeight(bool) = 0;
     virtual void setFullscreenSupported(bool) = 0;
     virtual void setHyperlinkAuditingEnabled(bool) = 0;
diff --git a/third_party/boringssl/BUILD.gn b/third_party/boringssl/BUILD.gn
index 4016f550..effa2d3 100644
--- a/third_party/boringssl/BUILD.gn
+++ b/third_party/boringssl/BUILD.gn
@@ -63,6 +63,7 @@
   source_set("boringssl_asm") {
     visibility = [ ":*" ]  # Only targets in this file can depend on this.
 
+    defines = []
     sources = []
     asmflags = []
     include_dirs = [ "src/include" ]
diff --git a/third_party/sqlite/amalgamation/sqlite3.c b/third_party/sqlite/amalgamation/sqlite3.c
index 0d9b5177..58981ca9 100644
--- a/third_party/sqlite/amalgamation/sqlite3.c
+++ b/third_party/sqlite/amalgamation/sqlite3.c
@@ -159422,11 +159422,11 @@
 */
 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
   const UChar *zInput;
-  UChar *zOutput;
+  UChar *zOutput = 0;
   int nInput;
-  int nOutput;
-
-  UErrorCode status = U_ZERO_ERROR;
+  int nOut;
+  int cnt;
+  UErrorCode status;
   const char *zLocale = 0;
 
   assert(nArg==1 || nArg==2);
@@ -159438,45 +159438,34 @@
   if( !zInput ){
     return;
   }
-  nOutput = nInput = sqlite3_value_bytes16(apArg[0]);
-
-  zOutput = sqlite3_malloc(nOutput);
-  if( !zOutput ){
+  nOut = nInput = sqlite3_value_bytes16(apArg[0]);
+  if( nOut==0 ){
+    sqlite3_result_text16(p, "", 0, SQLITE_STATIC);
     return;
   }
 
-  if( sqlite3_user_data(p) ){
-    nOutput = u_strToUpper(
-        zOutput, nOutput/2, zInput, nInput/2, zLocale, &status) * 2;
-  }else{
-    nOutput = u_strToLower(
-        zOutput, nOutput/2, zInput, nInput/2, zLocale, &status) * 2;
-  }
-
-  if ( status == U_BUFFER_OVERFLOW_ERROR ) {
-    UChar* newOutput = sqlite3_realloc(zOutput, nOutput);
-    if( !newOutput ){
+  for(cnt=0; cnt<2; cnt++){
+    UChar *zNew = sqlite3_realloc(zOutput, nOut);
+    if( zNew==0 ){
       sqlite3_free(zOutput);
+      sqlite3_result_error_nomem(p);
       return;
     }
-    zOutput = newOutput;
+    zOutput = zNew;
     status = U_ZERO_ERROR;
     if( sqlite3_user_data(p) ){
-      nOutput = u_strToUpper(
-          zOutput, nOutput/2, zInput, nInput/2, zLocale, &status) * 2;
+      nOut = 2*u_strToUpper(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
     }else{
-      nOutput = u_strToLower(
-          zOutput, nOutput/2, zInput, nInput/2, zLocale, &status) * 2;
+      nOut = 2*u_strToLower(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
+    }
+    if( !U_SUCCESS(status) ){
+      if( status==U_BUFFER_OVERFLOW_ERROR ) continue;
+      icuFunctionError(p,
+          sqlite3_user_data(p) ? "u_strToUpper()" : "u_strToLower", status);
+      return;
     }
   }
-
-  if( U_FAILURE(status) ){
-    icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
-    sqlite3_free(zOutput);
-    return;
-  }
-
-  sqlite3_result_text16(p, zOutput, nOutput, xFree);
+  sqlite3_result_text16(p, zOutput, nOut, xFree);
 }
 
 /*
diff --git a/third_party/sqlite/patches/0013-backport-Fix-buffer-overrun-in-ICU-extension-s-casem.patch b/third_party/sqlite/patches/0013-backport-Fix-buffer-overrun-in-ICU-extension-s-casem.patch
new file mode 100644
index 0000000..d18fd15
--- /dev/null
+++ b/third_party/sqlite/patches/0013-backport-Fix-buffer-overrun-in-ICU-extension-s-casem.patch
@@ -0,0 +1,119 @@
+From 0d13e8740021aeeb849662f03f49720287cabe0c Mon Sep 17 00:00:00 2001
+From: Scott Hess <shess@chromium.org>
+Date: Fri, 26 Feb 2016 10:49:33 -0800
+Subject: [PATCH 13/13] [backport] Fix buffer overrun in ICU extension's
+ casemap functions.
+
+Original Chromium CL at https://codereview.chromium.org/1704103002
+
+"Fix sqlite3's handling of casemapping result 3 times as long as input"
+
+SQLite interpretation at http://www.sqlite.org/src/info/b8dc1b9f5d413000
+
+"Fix a potential buffer overflow in the ICU upper() function."
+
+BUG=586079
+---
+ third_party/sqlite/src/ext/icu/icu.c | 48 +++++++++++++++++++++---------------
+ third_party/sqlite/src/test/icu.test |  9 +++++++
+ 2 files changed, 37 insertions(+), 20 deletions(-)
+
+diff --git a/third_party/sqlite/src/ext/icu/icu.c b/third_party/sqlite/src/ext/icu/icu.c
+index 5654366..263cd98 100644
+--- a/third_party/sqlite/src/ext/icu/icu.c
++++ b/third_party/sqlite/src/ext/icu/icu.c
+@@ -355,11 +355,11 @@ static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
+ */
+ static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
+   const UChar *zInput;
+-  UChar *zOutput;
++  UChar *zOutput = 0;
+   int nInput;
+-  int nOutput;
+-
+-  UErrorCode status = U_ZERO_ERROR;
++  int nOut;
++  int cnt;
++  UErrorCode status;
+   const char *zLocale = 0;
+ 
+   assert(nArg==1 || nArg==2);
+@@ -371,26 +371,34 @@ static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
+   if( !zInput ){
+     return;
+   }
+-  nInput = sqlite3_value_bytes16(apArg[0]);
+-
+-  nOutput = nInput * 2 + 2;
+-  zOutput = sqlite3_malloc(nOutput);
+-  if( !zOutput ){
++  nOut = nInput = sqlite3_value_bytes16(apArg[0]);
++  if( nOut==0 ){
++    sqlite3_result_text16(p, "", 0, SQLITE_STATIC);
+     return;
+   }
+ 
+-  if( sqlite3_user_data(p) ){
+-    u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
+-  }else{
+-    u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
+-  }
+-
+-  if( !U_SUCCESS(status) ){
+-    icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
+-    return;
++  for(cnt=0; cnt<2; cnt++){
++    UChar *zNew = sqlite3_realloc(zOutput, nOut);
++    if( zNew==0 ){
++      sqlite3_free(zOutput);
++      sqlite3_result_error_nomem(p);
++      return;
++    }
++    zOutput = zNew;
++    status = U_ZERO_ERROR;
++    if( sqlite3_user_data(p) ){
++      nOut = 2*u_strToUpper(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
++    }else{
++      nOut = 2*u_strToLower(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
++    }
++    if( !U_SUCCESS(status) ){
++      if( status==U_BUFFER_OVERFLOW_ERROR ) continue;
++      icuFunctionError(p,
++          sqlite3_user_data(p) ? "u_strToUpper()" : "u_strToLower", status);
++      return;
++    }
+   }
+-
+-  sqlite3_result_text16(p, zOutput, -1, xFree);
++  sqlite3_result_text16(p, zOutput, nOut, xFree);
+ }
+ 
+ /*
+diff --git a/third_party/sqlite/src/test/icu.test b/third_party/sqlite/src/test/icu.test
+index 73cb9b9..743bcfa 100644
+--- a/third_party/sqlite/src/test/icu.test
++++ b/third_party/sqlite/src/test/icu.test
+@@ -72,6 +72,10 @@ test_expr icu-2.6 {i1=$::OGRAVE} {upper(i1)}     $::OGRAVE
+ test_expr icu-2.7 {i1=$::szlig} {upper(i1)}      "SS"
+ test_expr icu-2.8 {i1='SS'} {lower(i1)}          "ss"
+ 
++do_execsql_test icu-2.9 {
++  SELECT upper(char(0xfb04,0xfb04,0xfb04,0xfb04));
++} {FFLFFLFFLFFL}
++
+ # In turkish (locale="tr_TR"), the lower case version of I
+ # is "small dotless i" (code point 0x131 (decimal 305)).
+ #
+@@ -133,4 +137,9 @@ do_catchsql_test icu-5.4 {
+ do_catchsql_test icu-5.4 { SELECT 'abc' REGEXP }    {1 {near " ": syntax error}}
+ do_catchsql_test icu-5.5 { SELECT 'abc' REGEXP, 1 } {1 {near ",": syntax error}}
+ 
++
++do_malloc_test icu-6.10 -sqlbody {
++  SELECT upper(char(0xfb04,0xdf,0xfb04,0xe8,0xfb04));
++}
++
+ finish_test
+-- 
+2.7.0
+
diff --git a/third_party/sqlite/patches/0013-icu-Fix-buffer-overflow-when-case-mapping-expands-to.patch b/third_party/sqlite/patches/0013-icu-Fix-buffer-overflow-when-case-mapping-expands-to.patch
deleted file mode 100644
index 9239314e..0000000
--- a/third_party/sqlite/patches/0013-icu-Fix-buffer-overflow-when-case-mapping-expands-to.patch
+++ /dev/null
@@ -1,101 +0,0 @@
-From e2beb15e5092bd882ba261e403daf76ef1b26456 Mon Sep 17 00:00:00 2001
-From: Scott Hess <shess@chromium.org>
-Date: Fri, 26 Feb 2016 10:49:33 -0800
-Subject: [PATCH 13/13] [icu] Fix buffer overflow when case mapping expands too
- far.
-
-Previously the buffer was doubled in size to accomodate cases where the
-case-mapped version was larger, but some cases expand by more than
-double.  Detect U_BUFFER_OVERFLOW_ERROR and expand to the provided size.
-
-Original Chromium checkin:
-https://codereview.chromium.org/1704103002
----
- third_party/sqlite/src/ext/icu/icu.c | 31 +++++++++++++++++++++++++------
- third_party/sqlite/src/test/icu.test |  7 +++++++
- 2 files changed, 32 insertions(+), 6 deletions(-)
-
-diff --git a/third_party/sqlite/src/ext/icu/icu.c b/third_party/sqlite/src/ext/icu/icu.c
-index 7e2b800..d384f71 100644
---- a/third_party/sqlite/src/ext/icu/icu.c
-+++ b/third_party/sqlite/src/ext/icu/icu.c
-@@ -341,26 +341,45 @@ static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
-   if( !zInput ){
-     return;
-   }
--  nInput = sqlite3_value_bytes16(apArg[0]);
-+  nOutput = nInput = sqlite3_value_bytes16(apArg[0]);
- 
--  nOutput = nInput * 2 + 2;
-   zOutput = sqlite3_malloc(nOutput);
-   if( !zOutput ){
-     return;
-   }
- 
-   if( sqlite3_user_data(p) ){
--    u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
-+    nOutput = u_strToUpper(
-+        zOutput, nOutput/2, zInput, nInput/2, zLocale, &status) * 2;
-   }else{
--    u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
-+    nOutput = u_strToLower(
-+        zOutput, nOutput/2, zInput, nInput/2, zLocale, &status) * 2;
-   }
- 
--  if( !U_SUCCESS(status) ){
-+  if ( status == U_BUFFER_OVERFLOW_ERROR ) {
-+    UChar* newOutput = sqlite3_realloc(zOutput, nOutput);
-+    if( !newOutput ){
-+      sqlite3_free(zOutput);
-+      return;
-+    }
-+    zOutput = newOutput;
-+    status = U_ZERO_ERROR;
-+    if( sqlite3_user_data(p) ){
-+      nOutput = u_strToUpper(
-+          zOutput, nOutput/2, zInput, nInput/2, zLocale, &status) * 2;
-+    }else{
-+      nOutput = u_strToLower(
-+          zOutput, nOutput/2, zInput, nInput/2, zLocale, &status) * 2;
-+    }
-+  }
-+
-+  if( U_FAILURE(status) ){
-     icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
-+    sqlite3_free(zOutput);
-     return;
-   }
- 
--  sqlite3_result_text16(p, zOutput, -1, xFree);
-+  sqlite3_result_text16(p, zOutput, nOutput, xFree);
- }
- 
- /*
-diff --git a/third_party/sqlite/src/test/icu.test b/third_party/sqlite/src/test/icu.test
-index 73cb9b9..22948aa 100644
---- a/third_party/sqlite/src/test/icu.test
-+++ b/third_party/sqlite/src/test/icu.test
-@@ -56,6 +56,10 @@ set ::ograve "\xF2"
- #
- set ::szlig "\xDF" 
- 
-+# U+FB03 (ffi ligature) and U+FB04 (ffl ligature). They're uppercased
-+# to 'FFI' and 'FFL'.
-+set ::ffi_ffl "\ufb03\ufb04"
-+
- # Tests of the upper()/lower() functions.
- #
- test_expr icu-2.1 {i1='HellO WorlD'} {upper(i1)} {HELLO WORLD}
-@@ -72,6 +76,9 @@ test_expr icu-2.6 {i1=$::OGRAVE} {upper(i1)}     $::OGRAVE
- test_expr icu-2.7 {i1=$::szlig} {upper(i1)}      "SS"
- test_expr icu-2.8 {i1='SS'} {lower(i1)}          "ss"
- 
-+test_expr icu-2.9 {i1=$::ffi_ffl} {upper(i1)}      "FFIFFL"
-+test_expr icu-2.10 {i1=$::ffi_ffl} {lower(i1)}      $::ffi_ffl
-+
- # In turkish (locale="tr_TR"), the lower case version of I
- # is "small dotless i" (code point 0x131 (decimal 305)).
- #
--- 
-2.7.0
-
diff --git a/third_party/sqlite/src/ext/icu/icu.c b/third_party/sqlite/src/ext/icu/icu.c
index d384f71..da34f3b1 100644
--- a/third_party/sqlite/src/ext/icu/icu.c
+++ b/third_party/sqlite/src/ext/icu/icu.c
@@ -325,11 +325,11 @@
 */
 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
   const UChar *zInput;
-  UChar *zOutput;
+  UChar *zOutput = 0;
   int nInput;
-  int nOutput;
-
-  UErrorCode status = U_ZERO_ERROR;
+  int nOut;
+  int cnt;
+  UErrorCode status;
   const char *zLocale = 0;
 
   assert(nArg==1 || nArg==2);
@@ -341,45 +341,34 @@
   if( !zInput ){
     return;
   }
-  nOutput = nInput = sqlite3_value_bytes16(apArg[0]);
-
-  zOutput = sqlite3_malloc(nOutput);
-  if( !zOutput ){
+  nOut = nInput = sqlite3_value_bytes16(apArg[0]);
+  if( nOut==0 ){
+    sqlite3_result_text16(p, "", 0, SQLITE_STATIC);
     return;
   }
 
-  if( sqlite3_user_data(p) ){
-    nOutput = u_strToUpper(
-        zOutput, nOutput/2, zInput, nInput/2, zLocale, &status) * 2;
-  }else{
-    nOutput = u_strToLower(
-        zOutput, nOutput/2, zInput, nInput/2, zLocale, &status) * 2;
-  }
-
-  if ( status == U_BUFFER_OVERFLOW_ERROR ) {
-    UChar* newOutput = sqlite3_realloc(zOutput, nOutput);
-    if( !newOutput ){
+  for(cnt=0; cnt<2; cnt++){
+    UChar *zNew = sqlite3_realloc(zOutput, nOut);
+    if( zNew==0 ){
       sqlite3_free(zOutput);
+      sqlite3_result_error_nomem(p);
       return;
     }
-    zOutput = newOutput;
+    zOutput = zNew;
     status = U_ZERO_ERROR;
     if( sqlite3_user_data(p) ){
-      nOutput = u_strToUpper(
-          zOutput, nOutput/2, zInput, nInput/2, zLocale, &status) * 2;
+      nOut = 2*u_strToUpper(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
     }else{
-      nOutput = u_strToLower(
-          zOutput, nOutput/2, zInput, nInput/2, zLocale, &status) * 2;
+      nOut = 2*u_strToLower(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
+    }
+    if( !U_SUCCESS(status) ){
+      if( status==U_BUFFER_OVERFLOW_ERROR ) continue;
+      icuFunctionError(p,
+          sqlite3_user_data(p) ? "u_strToUpper()" : "u_strToLower", status);
+      return;
     }
   }
-
-  if( U_FAILURE(status) ){
-    icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
-    sqlite3_free(zOutput);
-    return;
-  }
-
-  sqlite3_result_text16(p, zOutput, nOutput, xFree);
+  sqlite3_result_text16(p, zOutput, nOut, xFree);
 }
 
 /*
diff --git a/third_party/sqlite/src/test/icu.test b/third_party/sqlite/src/test/icu.test
index 22948aad..743bcfa 100644
--- a/third_party/sqlite/src/test/icu.test
+++ b/third_party/sqlite/src/test/icu.test
@@ -56,10 +56,6 @@
 #
 set ::szlig "\xDF" 
 
-# U+FB03 (ffi ligature) and U+FB04 (ffl ligature). They're uppercased
-# to 'FFI' and 'FFL'.
-set ::ffi_ffl "\ufb03\ufb04"
-
 # Tests of the upper()/lower() functions.
 #
 test_expr icu-2.1 {i1='HellO WorlD'} {upper(i1)} {HELLO WORLD}
@@ -76,8 +72,9 @@
 test_expr icu-2.7 {i1=$::szlig} {upper(i1)}      "SS"
 test_expr icu-2.8 {i1='SS'} {lower(i1)}          "ss"
 
-test_expr icu-2.9 {i1=$::ffi_ffl} {upper(i1)}      "FFIFFL"
-test_expr icu-2.10 {i1=$::ffi_ffl} {lower(i1)}      $::ffi_ffl
+do_execsql_test icu-2.9 {
+  SELECT upper(char(0xfb04,0xfb04,0xfb04,0xfb04));
+} {FFLFFLFFLFFL}
 
 # In turkish (locale="tr_TR"), the lower case version of I
 # is "small dotless i" (code point 0x131 (decimal 305)).
@@ -140,4 +137,9 @@
 do_catchsql_test icu-5.4 { SELECT 'abc' REGEXP }    {1 {near " ": syntax error}}
 do_catchsql_test icu-5.5 { SELECT 'abc' REGEXP, 1 } {1 {near ",": syntax error}}
 
+
+do_malloc_test icu-6.10 -sqlbody {
+  SELECT upper(char(0xfb04,0xdf,0xfb04,0xe8,0xfb04));
+}
+
 finish_test
diff --git a/tools/gn/label.cc b/tools/gn/label.cc
index 94c0e718..4545525c 100644
--- a/tools/gn/label.cc
+++ b/tools/gn/label.cc
@@ -99,16 +99,13 @@
   size_t offset = 0;
 #if defined(OS_WIN)
   if (IsPathAbsolute(input)) {
-    if (input[0] != '/') {
-      *err = Err(original_value, "Bad absolute path.",
-                 "Absolute paths must be of the form /C:\\ but this is \"" +
-                     input.as_string() + "\".");
-      return false;
-    }
-    if (input.size() > 3 && input[2] == ':' && IsSlash(input[3]) &&
-        base::IsAsciiAlpha(input[1])) {
+    size_t drive_letter_pos = input[0] == '/' ? 1 : 0;
+    if (input.size() > drive_letter_pos + 2 &&
+        input[drive_letter_pos + 1] == ':' &&
+        IsSlash(input[drive_letter_pos + 2]) &&
+        base::IsAsciiAlpha(input[drive_letter_pos])) {
       // Skip over the drive letter colon.
-      offset = 3;
+      offset = drive_letter_pos + 2;
     }
   }
 #endif
diff --git a/tools/gn/label_pattern.cc b/tools/gn/label_pattern.cc
index e107ba4..a330b3b 100644
--- a/tools/gn/label_pattern.cc
+++ b/tools/gn/label_pattern.cc
@@ -130,16 +130,12 @@
   size_t offset = 0;
 #if defined(OS_WIN)
   if (IsPathAbsolute(str)) {
-    if (str[0] != '/') {
-      *err = Err(value, "Bad absolute path.",
-                 "Absolute paths must be of the form /C:\\ but this is \"" +
-                     str.as_string() + "\".");
-      return LabelPattern();
-    }
-    if (str.size() > 3 && str[2] == ':' && IsSlash(str[3]) &&
-        base::IsAsciiAlpha(str[1])) {
+    size_t drive_letter_pos = str[0] == '/' ? 1 : 0;
+    if (str.size() > drive_letter_pos + 2 && str[drive_letter_pos + 1] == ':' &&
+        IsSlash(str[drive_letter_pos + 2]) &&
+        base::IsAsciiAlpha(str[drive_letter_pos])) {
       // Skip over the drive letter colon.
-      offset = 3;
+      offset = drive_letter_pos + 2;
     }
   }
 #endif
diff --git a/tools/gn/label_pattern_unittest.cc b/tools/gn/label_pattern_unittest.cc
index 19e2530..2154af1 100644
--- a/tools/gn/label_pattern_unittest.cc
+++ b/tools/gn/label_pattern_unittest.cc
@@ -28,36 +28,46 @@
   SourceDir current_dir("//foo/");
   PatternCase cases[] = {
     // Missing stuff.
-    { "", false, LabelPattern::MATCH, "", "", "" },
-    { ":", false, LabelPattern::MATCH, "", "", "" },
+    {"", false, LabelPattern::MATCH, "", "", ""},
+    {":", false, LabelPattern::MATCH, "", "", ""},
     // Normal things.
-    { ":bar", true, LabelPattern::MATCH, "//foo/", "bar", "" },
-    { "//la:bar", true, LabelPattern::MATCH, "//la/", "bar", "" },
-    { "*", true, LabelPattern::RECURSIVE_DIRECTORY, "", "", "" },
-    { ":*", true, LabelPattern::DIRECTORY, "//foo/", "", "" },
-    { "la:*", true, LabelPattern::DIRECTORY, "//foo/la/", "", "" },
-    { "la/*:*", true, LabelPattern::RECURSIVE_DIRECTORY, "//foo/la/", "", "" },
-    { "//la:*", true, LabelPattern::DIRECTORY, "//la/", "", "" },
-    { "./*", true, LabelPattern::RECURSIVE_DIRECTORY, "//foo/", "", "" },
-    { "foo/*", true, LabelPattern::RECURSIVE_DIRECTORY, "//foo/foo/", "", "" },
-    { "//l/*", true, LabelPattern::RECURSIVE_DIRECTORY, "//l/", "", "" },
+    {":bar", true, LabelPattern::MATCH, "//foo/", "bar", ""},
+    {"//la:bar", true, LabelPattern::MATCH, "//la/", "bar", ""},
+    {"*", true, LabelPattern::RECURSIVE_DIRECTORY, "", "", ""},
+    {":*", true, LabelPattern::DIRECTORY, "//foo/", "", ""},
+    {"la:*", true, LabelPattern::DIRECTORY, "//foo/la/", "", ""},
+    {"la/*:*", true, LabelPattern::RECURSIVE_DIRECTORY, "//foo/la/", "", ""},
+    {"//la:*", true, LabelPattern::DIRECTORY, "//la/", "", ""},
+    {"./*", true, LabelPattern::RECURSIVE_DIRECTORY, "//foo/", "", ""},
+    {"foo/*", true, LabelPattern::RECURSIVE_DIRECTORY, "//foo/foo/", "", ""},
+    {"//l/*", true, LabelPattern::RECURSIVE_DIRECTORY, "//l/", "", ""},
     // Toolchains.
-    { "//foo()", true, LabelPattern::MATCH, "//foo/", "foo", "" },
-    { "//foo(//bar)", true, LabelPattern::MATCH, "//foo/", "foo", "//bar:bar" },
-    { "//foo:*(//bar)", true, LabelPattern::DIRECTORY, "//foo/", "",
-      "//bar:bar" },
-    { "//foo/*(//bar)", true, LabelPattern::RECURSIVE_DIRECTORY, "//foo/", "",
-      "//bar:bar" },
+    {"//foo()", true, LabelPattern::MATCH, "//foo/", "foo", ""},
+    {"//foo(//bar)", true, LabelPattern::MATCH, "//foo/", "foo", "//bar:bar"},
+    {"//foo:*(//bar)", true, LabelPattern::DIRECTORY, "//foo/", "",
+     "//bar:bar"},
+    {"//foo/*(//bar)", true, LabelPattern::RECURSIVE_DIRECTORY, "//foo/", "",
+     "//bar:bar"},
     // Wildcards in invalid places.
-    { "*foo*:bar", false, LabelPattern::MATCH, "", "", "" },
-    { "foo*:*bar", false, LabelPattern::MATCH, "", "", "" },
-    { "*foo:bar", false, LabelPattern::MATCH, "", "", "" },
-    { "foo:bar*", false, LabelPattern::MATCH, "", "", "" },
-    { "*:*", true, LabelPattern::RECURSIVE_DIRECTORY, "", "", "" },
+    {"*foo*:bar", false, LabelPattern::MATCH, "", "", ""},
+    {"foo*:*bar", false, LabelPattern::MATCH, "", "", ""},
+    {"*foo:bar", false, LabelPattern::MATCH, "", "", ""},
+    {"foo:bar*", false, LabelPattern::MATCH, "", "", ""},
+    {"*:*", true, LabelPattern::RECURSIVE_DIRECTORY, "", "", ""},
     // Invalid toolchain stuff.
-    { "//foo(//foo/bar:*)", false, LabelPattern::MATCH, "", "", "" },
-    { "//foo/*(*)", false, LabelPattern::MATCH, "", "", "" },
-    { "//foo(//bar", false, LabelPattern::MATCH, "", "", "" },
+    {"//foo(//foo/bar:*)", false, LabelPattern::MATCH, "", "", ""},
+    {"//foo/*(*)", false, LabelPattern::MATCH, "", "", ""},
+    {"//foo(//bar", false, LabelPattern::MATCH, "", "", ""},
+    // Absolute paths.
+    {"/la/*", true, LabelPattern::RECURSIVE_DIRECTORY, "/la/", "", ""},
+    {"/la:bar", true, LabelPattern::MATCH, "/la/", "bar", ""},
+#if defined(OS_WIN)
+    {"/C:/la/*", true, LabelPattern::RECURSIVE_DIRECTORY, "/C:/la/", "", ""},
+    {"C:/la/*", true, LabelPattern::RECURSIVE_DIRECTORY, "/C:/la/", "", ""},
+    {"/C:/la:bar", true, LabelPattern::MATCH, "/C:/la/", "bar", ""},
+    {"C:/la:bar", true, LabelPattern::MATCH, "/C:/la/", "bar", ""},
+    {"C:foo", true, LabelPattern::MATCH, "//foo/C/", "foo", ""},
+#endif
   };
 
   for (size_t i = 0; i < arraysize(cases); i++) {
diff --git a/tools/gn/label_unittest.cc b/tools/gn/label_unittest.cc
index 37c097f2..986aa9b5 100644
--- a/tools/gn/label_unittest.cc
+++ b/tools/gn/label_unittest.cc
@@ -27,46 +27,48 @@
 
 TEST(Label, Resolve) {
   ParseDepStringCase cases[] = {
-      // cur         input                        succ   expected dir          name    tc dir    tc name
-      { "//chrome/", "",                          false, "",                   "",     "",       "" },
-      { "//chrome/", "/",                         false, "",                   "",     "",       "" },
-      { "//chrome/", ":",                         false, "",                   "",     "",       "" },
-      { "//chrome/", "/:",                        false, "",                   "",     "",       "" },
-      { "//chrome/", "blah",                      true,  "//chrome/blah/",     "blah", "//t/",   "d" },
-      { "//chrome/", "blah:bar",                  true,  "//chrome/blah/",     "bar",  "//t/",   "d" },
-      // Absolute paths.
-      { "//chrome/", "/chrome:bar",               true , "/chrome/",           "bar",  "//t/",   "d" },
-      { "//chrome/", "/chrome/:bar",              true,  "/chrome/",           "bar",  "//t/",   "d" },
+    {"//chrome/", "", false, "", "", "", ""},
+    {"//chrome/", "/", false, "", "", "", ""},
+    {"//chrome/", ":", false, "", "", "", ""},
+    {"//chrome/", "/:", false, "", "", "", ""},
+    {"//chrome/", "blah", true, "//chrome/blah/", "blah", "//t/", "d"},
+    {"//chrome/", "blah:bar", true, "//chrome/blah/", "bar", "//t/", "d"},
+    // Absolute paths.
+    {"//chrome/", "/chrome:bar", true, "/chrome/", "bar", "//t/", "d"},
+    {"//chrome/", "/chrome/:bar", true, "/chrome/", "bar", "//t/", "d"},
 #if defined(OS_WIN)
-      { "//chrome/", "/C:/chrome:bar",            true , "/C:/chrome/",        "bar",  "//t/",   "d" },
-      { "//chrome/", "/C:/chrome/:bar",           true,  "/C:/chrome/",        "bar",  "//t/",   "d" },
-      { "//chrome/", "C:/chrome:bar",             false, "",                   "",     "",       "" },
+    {"//chrome/", "/C:/chrome:bar", true, "/C:/chrome/", "bar", "//t/", "d"},
+    {"//chrome/", "/C:/chrome/:bar", true, "/C:/chrome/", "bar", "//t/", "d"},
+    {"//chrome/", "C:/chrome:bar", true, "/C:/chrome/", "bar", "//t/", "d"},
 #endif
-      // Refers to root dir.
-      { "//chrome/", "//:bar",                    true,  "//",                 "bar",  "//t/",   "d" },
-      // Implicit directory
-      { "//chrome/", ":bar",                      true,  "//chrome/",          "bar",  "//t/",   "d" },
-      { "//chrome/renderer/", ":bar",             true,  "//chrome/renderer/", "bar",  "//t/",   "d" },
-      // Implicit names.
-      { "//chrome/", "//base",                    true,  "//base/",            "base", "//t/",   "d" },
-      { "//chrome/", "//base/i18n",               true,  "//base/i18n/",       "i18n", "//t/",   "d" },
-      { "//chrome/", "//base/i18n:foo",           true,  "//base/i18n/",       "foo",  "//t/",   "d" },
-      { "//chrome/", "//",                        false, "",                   "",     "",       "" },
-      // Toolchain parsing.
-      { "//chrome/", "//chrome:bar(//t:n)",       true,  "//chrome/",          "bar",  "//t/",   "n" },
-      { "//chrome/", "//chrome:bar(//t)",         true,  "//chrome/",          "bar",  "//t/",   "t" },
-      { "//chrome/", "//chrome:bar(//t:)",        true,  "//chrome/",          "bar",  "//t/",   "t" },
-      { "//chrome/", "//chrome:bar()",            true,  "//chrome/",          "bar",  "//t/",   "d" },
-      { "//chrome/", "//chrome:bar(foo)",         true,  "//chrome/",          "bar",  "//chrome/foo/", "foo" },
-      { "//chrome/", "//chrome:bar(:foo)",        true,  "//chrome/",          "bar",  "//chrome/",     "foo" },
-      // TODO(brettw) it might be nice to make this an error:
-      //{ "//chrome/", "//chrome:bar())",           false, "",                   "",     "",       "" },
-      { "//chrome/", "//chrome:bar(//t:bar(tc))", false, "",                   "",     "",       "" },
-      { "//chrome/", "//chrome:bar(()",           false, "",                   "",     "",       "" },
-      { "//chrome/", "(t:b)",                     false, "",                   "",     "",       "" },
-      { "//chrome/", ":bar(//t/b)",               true,  "//chrome/",          "bar",  "//t/b/", "b" },
-      { "//chrome/", ":bar(/t/b)",                true,  "//chrome/",          "bar",  "/t/b/",  "b" },
-      { "//chrome/", ":bar(t/b)",                 true,  "//chrome/",          "bar",  "//chrome/t/b/", "b" },
+    // Refers to root dir.
+    {"//chrome/", "//:bar", true, "//", "bar", "//t/", "d"},
+    // Implicit directory
+    {"//chrome/", ":bar", true, "//chrome/", "bar", "//t/", "d"},
+    {"//chrome/renderer/", ":bar", true, "//chrome/renderer/", "bar", "//t/",
+     "d"},
+    // Implicit names.
+    {"//chrome/", "//base", true, "//base/", "base", "//t/", "d"},
+    {"//chrome/", "//base/i18n", true, "//base/i18n/", "i18n", "//t/", "d"},
+    {"//chrome/", "//base/i18n:foo", true, "//base/i18n/", "foo", "//t/", "d"},
+    {"//chrome/", "//", false, "", "", "", ""},
+    // Toolchain parsing.
+    {"//chrome/", "//chrome:bar(//t:n)", true, "//chrome/", "bar", "//t/", "n"},
+    {"//chrome/", "//chrome:bar(//t)", true, "//chrome/", "bar", "//t/", "t"},
+    {"//chrome/", "//chrome:bar(//t:)", true, "//chrome/", "bar", "//t/", "t"},
+    {"//chrome/", "//chrome:bar()", true, "//chrome/", "bar", "//t/", "d"},
+    {"//chrome/", "//chrome:bar(foo)", true, "//chrome/", "bar",
+     "//chrome/foo/", "foo"},
+    {"//chrome/", "//chrome:bar(:foo)", true, "//chrome/", "bar", "//chrome/",
+     "foo"},
+    // TODO(brettw) it might be nice to make this an error:
+    //{"//chrome/", "//chrome:bar())", false, "", "", "", "" },
+    {"//chrome/", "//chrome:bar(//t:bar(tc))", false, "", "", "", ""},
+    {"//chrome/", "//chrome:bar(()", false, "", "", "", ""},
+    {"//chrome/", "(t:b)", false, "", "", "", ""},
+    {"//chrome/", ":bar(//t/b)", true, "//chrome/", "bar", "//t/b/", "b"},
+    {"//chrome/", ":bar(/t/b)", true, "//chrome/", "bar", "/t/b/", "b"},
+    {"//chrome/", ":bar(t/b)", true, "//chrome/", "bar", "//chrome/t/b/", "b"},
   };
 
   Label default_toolchain(SourceDir("//t/"), "d");
@@ -82,12 +84,9 @@
         Label::Resolve(SourceDir(cur.cur_dir), default_toolchain, v, &err);
     EXPECT_EQ(cur.success, !err.has_error()) << i << " " << cur.str;
     if (!err.has_error() && cur.success) {
-      EXPECT_EQ(cur.expected_dir, result.dir().value())
-          << i << " " << cur.str;
-      EXPECT_EQ(cur.expected_name, result.name())
-          << i << " " << cur.str;
-      EXPECT_EQ(cur.expected_toolchain_dir,
-                result.toolchain_dir().value())
+      EXPECT_EQ(cur.expected_dir, result.dir().value()) << i << " " << cur.str;
+      EXPECT_EQ(cur.expected_name, result.name()) << i << " " << cur.str;
+      EXPECT_EQ(cur.expected_toolchain_dir, result.toolchain_dir().value())
           << i << " " << cur.str;
       EXPECT_EQ(cur.expected_toolchain_name, result.toolchain_name())
           << i << " " << cur.str;
diff --git a/tools/ipc_fuzzer/fuzzer/fuzzer.cc b/tools/ipc_fuzzer/fuzzer/fuzzer.cc
index ba590212..1bb8ed06 100644
--- a/tools/ipc_fuzzer/fuzzer/fuzzer.cc
+++ b/tools/ipc_fuzzer/fuzzer/fuzzer.cc
@@ -1710,20 +1710,6 @@
 };
 
 template <>
-struct FuzzTraits<remoting::ScreenResolution> {
-  static bool Fuzz(remoting::ScreenResolution* p, Fuzzer* fuzzer) {
-    webrtc::DesktopSize dimensions = p->dimensions();
-    webrtc::DesktopVector dpi = p->dpi();
-    if (!FuzzParam(&dimensions, fuzzer))
-      return false;
-    if (!FuzzParam(&dpi, fuzzer))
-      return false;
-    *p = remoting::ScreenResolution(dimensions, dpi);
-    return true;
-  }
-};
-
-template <>
 struct FuzzTraits<SkBitmap> {
   static bool Fuzz(SkBitmap* p, Fuzzer* fuzzer) {
     // TODO(mbarbella): This should actually do something.
@@ -1888,73 +1874,6 @@
   }
 };
 
-template <>
-struct FuzzTraits<webrtc::DesktopSize> {
-  static bool Fuzz(webrtc::DesktopSize* p, Fuzzer* fuzzer) {
-    int32_t width = p->width();
-    int32_t height = p->height();
-    if (!FuzzParam(&width, fuzzer))
-      return false;
-    if (!FuzzParam(&height, fuzzer))
-      return false;
-    *p = webrtc::DesktopSize(width, height);
-    return true;
-  }
-};
-
-template <>
-struct FuzzTraits<webrtc::DesktopVector> {
-  static bool Fuzz(webrtc::DesktopVector* p, Fuzzer* fuzzer) {
-    int32_t x = p->x();
-    int32_t y = p->y();
-    if (!FuzzParam(&x, fuzzer))
-      return false;
-    if (!FuzzParam(&y, fuzzer))
-      return false;
-    p->set(x, y);
-    return true;
-  }
-};
-
-template <>
-struct FuzzTraits<webrtc::DesktopRect> {
-  static bool Fuzz(webrtc::DesktopRect* p, Fuzzer* fuzzer) {
-    int32_t left = p->left();
-    int32_t top = p->top();
-    int32_t right = p->right();
-    int32_t bottom = p->bottom();
-    if (!FuzzParam(&left, fuzzer))
-      return false;
-    if (!FuzzParam(&top, fuzzer))
-      return false;
-    if (!FuzzParam(&right, fuzzer))
-      return false;
-    if (!FuzzParam(&bottom, fuzzer))
-      return false;
-    *p = webrtc::DesktopRect::MakeLTRB(left, top, right, bottom);
-    return true;
-  }
-};
-
-template <>
-struct FuzzTraits<webrtc::MouseCursor> {
-  static bool Fuzz(webrtc::MouseCursor* p, Fuzzer* fuzzer) {
-    webrtc::DesktopVector hotspot = p->hotspot();
-    if (!FuzzParam(&hotspot, fuzzer))
-      return false;
-    p->set_hotspot(hotspot);
-
-    // TODO(mbarbella): Find a way to handle the size mutation properly.
-    if (!fuzzer->ShouldGenerate())
-      return false;
-
-    // Using a small size here to avoid OOM or overflow on image allocation.
-    webrtc::DesktopSize size(RandInRange(100), RandInRange(100));
-    p->set_image(new webrtc::BasicDesktopFrame(size));
-    return true;
-  }
-};
-
 // Redefine macros to generate generating from traits declarations.
 // STRUCT declarations cause corresponding STRUCT_TRAITS declarations to occur.
 #undef IPC_STRUCT_BEGIN
diff --git a/tools/ipc_fuzzer/message_lib/all_messages.h b/tools/ipc_fuzzer/message_lib/all_messages.h
index d846673a..cc60178 100644
--- a/tools/ipc_fuzzer/message_lib/all_messages.h
+++ b/tools/ipc_fuzzer/message_lib/all_messages.h
@@ -26,4 +26,3 @@
 #include "components/visitedlink/common/visitedlink_message_generator.h"
 #include "content/common/all_messages.h"
 #include "extensions/common/extension_message_generator.h"
-#include "remoting/host/chromoting_messages.h"
diff --git a/tools/mb/mb_config.pyl b/tools/mb/mb_config.pyl
index 43367b42..42e77ce 100644
--- a/tools/mb/mb_config.pyl
+++ b/tools/mb/mb_config.pyl
@@ -1797,7 +1797,7 @@
     },
 
     'lto': {
-       'gn_args': 'is_lto=true',
+       'gn_args': 'allow_posix_link_time_opt=true',
        'gyp_defines': 'use_lto=1',
      },
 
diff --git a/ui/OWNERS b/ui/OWNERS
index 05a964d..79875b5 100644
--- a/ui/OWNERS
+++ b/ui/OWNERS
@@ -4,6 +4,7 @@
 
 # Mac stuff
 avi@chromium.org
+ccameron@chromium.org
 
 per-file *.isolate=maruel@chromium.org
 per-file *.isolate=tandrii@chromium.org
diff --git a/ui/android/java/src/org/chromium/ui/resources/dynamics/ViewResourceInflater.java b/ui/android/java/src/org/chromium/ui/resources/dynamics/ViewResourceInflater.java
index 3d7b890..ddb5eb1 100644
--- a/ui/android/java/src/org/chromium/ui/resources/dynamics/ViewResourceInflater.java
+++ b/ui/android/java/src/org/chromium/ui/resources/dynamics/ViewResourceInflater.java
@@ -140,6 +140,7 @@
         // View must be inflated at this point. If it's not, do it now.
         if (mView == null) {
             inflate();
+            didViewSizeChange = true;
         }
 
         mIsInvalidated = true;
@@ -161,8 +162,7 @@
         } else {
             // When the View is not attached, we need to manually layout the View and
             // invalidate the resource in order to capture a new snapshot.
-            mView.measure(getWidthMeasureSpec(), getHeightMeasureSpec());
-            mView.layout(0, 0, getMeasuredWidth(), getMeasuredHeight());
+            layout();
             invalidateResource();
         }
     }
@@ -255,6 +255,14 @@
     }
 
     /**
+     * Lays out the View.
+     */
+    protected void layout() {
+        mView.measure(getWidthMeasureSpec(), getHeightMeasureSpec());
+        mView.layout(0, 0, getMeasuredWidth(), getMeasuredHeight());
+    }
+
+    /**
      * @return The View resource.
      */
     protected View getView() {
@@ -262,6 +270,13 @@
     }
 
     /**
+     * @return The Context used to inflate the View.
+     */
+    protected Context getContext() {
+        return mContext;
+    }
+
+    /**
      * Attach the View to the hierarchy.
      */
     private void attachView() {
diff --git a/ui/file_manager/file_manager/common/js/metrics_events.js b/ui/file_manager/file_manager/common/js/metrics_events.js
index d1f63aa..a8c068f 100644
--- a/ui/file_manager/file_manager/common/js/metrics_events.js
+++ b/ui/file_manager/file_manager/common/js/metrics_events.js
@@ -56,7 +56,8 @@
   ibfbhbegfkamboeglpnianlggahglbfi: 'Cloud Storage (FB)',
   pmnllmkmjilbojkpgplbdmckghmaocjh: 'Scan (FB)',
   mfhnnfciefdpolbelmfkpmhhmlkehbdf: 'File System for SMB/CIFS (YT)',
-  plmanjiaoflhcilcfdnjeffklbgejmje: 'Add MY Documents (KA)'
+  plmanjiaoflhcilcfdnjeffklbgejmje: 'Add MY Documents (KA)',
+  mljpablpddhocfbnokacjggdbmafjnon: 'Wicked Good Unarchiver (MF)'
 };
 
 /**
diff --git a/ui/file_manager/file_manager/foreground/css/file_manager.css b/ui/file_manager/file_manager/foreground/css/file_manager.css
index e9e0a5c..395ef1e 100644
--- a/ui/file_manager/file_manager/foreground/css/file_manager.css
+++ b/ui/file_manager/file_manager/foreground/css/file_manager.css
@@ -839,7 +839,7 @@
 
 #search-box.has-cursor input,
 #search-box.has-text input {
-  width: 218px;
+  width: 202px;
 }
 
 #search-box .clear {
@@ -851,9 +851,9 @@
   display: none;
   height: 16px;
   margin: 0;
-  position: absolute;
+  position: relative;
   right: 0;
-  top: 7px;
+  top: 2px;
   visibility: hidden;
   width: 16px;
 }
diff --git a/ui/file_manager/file_manager/main.html b/ui/file_manager/file_manager/main.html
index 02305b2..6539536 100644
--- a/ui/file_manager/file_manager/main.html
+++ b/ui/file_manager/file_manager/main.html
@@ -262,7 +262,7 @@
         <paper-input-container no-label-float>
           <input is="iron-input" type="search" tabindex="13"
                  i18n-values="aria-label:SEARCH_TEXT_LABEL;placeholder:SEARCH_TEXT_LABEL">
-          <span class="clear"></span>
+          <span class="clear" suffix></span>
         </paper-input-container>
       </div>
       <button id="refresh-button" class="icon-button" tabindex="14" hidden
diff --git a/ui/gl/gl_image_io_surface.h b/ui/gl/gl_image_io_surface.h
index 85f2ab4..134e931 100644
--- a/ui/gl/gl_image_io_surface.h
+++ b/ui/gl/gl_image_io_surface.h
@@ -73,7 +73,6 @@
   unsigned program_ = 0;
   int size_location_ = -1;
   unsigned vertex_buffer_ = 0;
-  unsigned yuv_textures_[2] = {};
 
   DISALLOW_COPY_AND_ASSIGN(GLImageIOSurface);
 };
diff --git a/ui/gl/gl_image_io_surface.mm b/ui/gl/gl_image_io_surface.mm
index e0d08003..1d404106 100644
--- a/ui/gl/gl_image_io_surface.mm
+++ b/ui/gl/gl_image_io_surface.mm
@@ -6,7 +6,9 @@
 
 #include <map>
 
+#include "base/callback_helpers.h"
 #include "base/lazy_instance.h"
+#include "base/mac/bind_objc_block.h"
 #include "base/mac/foundation_util.h"
 #include "base/strings/stringize_macros.h"
 #include "base/strings/stringprintf.h"
@@ -227,7 +229,6 @@
     glDeleteShader(fragment_shader_);
     glDeleteBuffersARB(1, &vertex_buffer_);
     glDeleteFramebuffersEXT(1, &framebuffer_);
-    glDeleteTextures(2, yuv_textures_);
   }
   io_surface_.reset();
 }
@@ -282,6 +283,19 @@
     return false;
   }
 
+  // Ensure that all textures bound to IOSurfaces be destroyed before the
+  // function exits. If they are not destroyed they may cause deadlocks between
+  // VTDecompressionSession at CGLContextDestroy.
+  // https://crbug.com/598388
+  unsigned y_texture = 0;
+  glGenTextures(1, &y_texture);
+  unsigned uv_texture = 0;
+  glGenTextures(1, &uv_texture);
+  base::ScopedClosureRunner destroy_resources_runner(base::BindBlock(^{
+    glDeleteTextures(1, &y_texture);
+    glDeleteTextures(1, &uv_texture);
+  }));
+
   if (!framebuffer_) {
     glGenFramebuffersEXT(1, &framebuffer_);
     vertex_buffer_ = gfx::GLHelper::SetupQuadVertexBuffer();
@@ -305,10 +319,6 @@
 
     glUniform1i(y_sampler_location, 0);
     glUniform1i(uv_sampler_location, 1);
-
-    glGenTextures(2, yuv_textures_);
-    DCHECK(yuv_textures_[0]);
-    DCHECK(yuv_textures_[1]);
   }
 
   CGLContextObj cgl_context =
@@ -326,7 +336,7 @@
 
     gfx::ScopedActiveTexture active_texture0(GL_TEXTURE0);
     gfx::ScopedTextureBinder texture_y_binder(GL_TEXTURE_RECTANGLE_ARB,
-                                              yuv_textures_[0]);
+                                              y_texture);
     cgl_error = CGLTexImageIOSurface2D(
         cgl_context, GL_TEXTURE_RECTANGLE_ARB, GL_RED, size_.width(),
         size_.height(), GL_RED, GL_UNSIGNED_BYTE, io_surface_.get(), 0);
@@ -338,7 +348,7 @@
     {
       gfx::ScopedActiveTexture active_texture1(GL_TEXTURE1);
       gfx::ScopedTextureBinder texture_uv_binder(GL_TEXTURE_RECTANGLE_ARB,
-                                                 yuv_textures_[1]);
+                                                 uv_texture);
       cgl_error = CGLTexImageIOSurface2D(
           cgl_context, GL_TEXTURE_RECTANGLE_ARB, GL_RG, size_.width() / 2,
           size_.height() / 2, GL_RG, GL_UNSIGNED_BYTE, io_surface_.get(), 1);